if判断
if <判断条件1>:
<执行1>
elif <判断条件2>:
<执行2>
else
<执行3>
只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
循环#
enumerate()
当需要显示序列index时,使用enumrate函数 enumrate(iterable[,start])
示例如下:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
zip()
当同时遍历两个或多个sequence时,使用zip函数,示例如下:
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print 'What is your {0}? It is {1}.'.format(q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
reversed()和 a[::-1]
倒序遍历sequence ,使用reversed函数:
>>> for i in reversed(xrange(1,10,2)):
... print i
...
9
7
5
3
1
另一种优雅的倒序实现方式 a[::-1]:
>>> a = [1,2,3,4,5]
>>> for i in a[::-1]
print i
sorted()
要按顺序遍历一个序列,使用sorted()函数返回一个新的排序列表而源列表不变。
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear
L[:] copy List
当遍历一个sequence时,需要改变sequence元素,推荐使用copy。示例代码如下:
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
List 拷贝代码:
>>> word = ['cat','dog']
>>> word_copy = word
>>> word.append('pig')
>>> word_copy
['cat', 'dog', 'pig']
>>> word_copy = word[:] # list copy
>>> word_copy
['cat', 'dog', 'pig']
>>> del word[0]
>>> word
['dog', 'pig']
>>> word_copy
['cat', 'dog', 'pig']
网友评论