1.三元操作符
>>> x,y=4,3
>>> if x < y:
... smaller = x;
... else:
... smaller = y;
...
>>> smaller
3
>>> smaller = 0;
>>> smaller = (x<y and [x] or [y])[0]
>>> smaller
3
>>> smaller = x if x <y else y;
>>> smaller
3
X if C else Y
2.迭代序列有三种方法。
通过序列项迭代:
>>> nameList=['Walter',"Nicole",'Steven','Henry']
>>> for eachName in nameList:
... print eachName, "Lim"
...
Walter Lim
Nicole Lim
Steven Lim
Henry Lim
通过序列索引迭代
>>> for nameIndex in range(len(nameList)):
... print "Liu,",nameList[nameIndex]
...
Liu, Walter
Liu, Nicole
Liu, Steven
Liu, Henry
使用项和索引迭代
使用enumerate()函数
>>> for i, eachLee in enumerate(nameList):
... print "%d %s Lee" % (i+1, eachLee)
...
1 Walter Lee
2 Nicole Lee
3 Steven Lee
4 Henry Lee
3.如果在需要子句块的地方不写任何语句,解释器会提示你语法错误。因此,Python提供了pass语句,它不做任何事情——即NOP(No OPeration).
4.在Python中,你可以在while和for循环中使用else语句。在循环中使用时,else子句只会在循环完成后执行,也就是说break语句也会跳过else块。
def showMaxFactor(num):
count = num/2;
while count > 1:
if num %count == 0:
print 'largest factor of %d is %d' % (num, count);
break;
count -= 1;
else:
print num, 'is prime';
for eachNum in range(10,21):
showMaxFactor(eachNum);
5.
列表解析:
[expr for iter_var in iterable] //核心是for循环,它迭代iterable对象的所有条目,前面的expr应用于序列的每个成员,最后的结果值是该表达式产生的列表。
[expr for iter_var in iterable if cond_expr] //这个语法会在迭代时过滤/捕获满足条件表达式cond_expr的序列成员
6.
生成器表达式:
并不是真正创建数字列表,而是返回一个生成器,这个生成器在每次计算出一个条目后,把这个条目“产生”出来,生成器表达式使用了“延迟计算”,所以在使用内存上更有效。
(expr for iter_var in iterable if cond_expr)
为了避免创建庞大的列表,我们可以使用生成器表达式来操作。
rows = [1,2,3,17];
def cols():
yield 56
yield 2
yield 1
x_product_pairs = ((i, j) for i in rows for j in cols());
for pair in x_product_pairs:
print pair