1
2
3
4
5
6
a, b, c = 1, 0, 2
d = a if b else c # 2
1 <= a < 2 # True, 1 < a and a <2
False == False == True # False, False == False and False == True
or_val = 2 or 3 # 2
and_val = 2 and 3 # 3
  • Python 可以同时给多个值赋值,只要 = 左右元素个数相同。实际上,就是 tuple packing(元组打包) 和 sequence unpacking(序列解包)。
  • Python 没有三元运算符 ? :,但是Python 2.5 新增了一个内置的条件表达式 a if b else c,即当 b 为真时,表达式的值为 a,否则,表达式的值为 c
  • Python 链式比较,是两边的分别和中间的比较,不是顺序比较。如:False == False == True,是 False == False and False == True,而不是 (False == False) == True
  • Python andor 表达式的返回值为表达式最后执行的值,如:2 and 3 and 1 - 1 的值为 0,因为,表达式最后执行的是 1 - 1。和 PHP 不一样,PHP 返回表达式的对错判断 true/1false/0

List Comprehensions - 列表推导式/列表解析

1
2
3
4
5
6
args = [ x**2 for x in range(-10, 10) if x > 0 ]
# it is the same as:
args = []
for x in range(-10, 10):
if x > 0:
args.append(x**2)

example2:

1
2
3
4
5
6
7
args = [(x, y) for x in range(1, 10) for y in range(6, 10) if x != y]
# it is the same as:
args = []
for x in range(1, 10):
for y in range(6, 10):
if x != y:
args.append((x, y))


1
2
3
with open('xx', 'x') as fp:
for line in iter(fp.readline, ''): # 遍历文件的每行直到为空
xxx

1
2
3
4
for i in range(10):
print(i)
else:
print('The for is not completed')

for 完全遍历完迭代对象时,else 语句执行。The for statement