遍历一个范围内的数字
for i in range(6):
print (i ** 2)
0
1
4
9
16
25
遍历集合
colors = ['red', 'green', 'blue', 'yellow']
for color in colors:
print (color)
red
green
blue
yellow
反向遍历集合
for color in reversed(colors):
print (color)
yellow
blue
green
red
遍历集合及其下标
for i, color in enumerate(colors):
print (i, '-->', color)
0 --> red
1 --> green
2 --> blue
3 --> yellow
遍历两个集合
names = ['raymond', 'rachel', 'mattthew']
colors = ['red', 'green', 'blue', 'yellow']
for name, color in zip(names, colors):
print (name, '-->', color)
raymond --> red
rachel --> green
mattthew --> blue
有序遍历
colors = ['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
print (color)
for color in sorted(colors, reverse = True):
print (color)
blue
green
red
yellow
yellow
red
green
blue
自定义排序顺序
colors = ['red', 'green', 'blue', 'yellow']
print (sorted(colors, key=len))
['red', 'blue', 'green', 'yellow']
列表解析和生成器
print (sum(i ** 2 for i in range(10)))
285