# 遍历字典 var1 = {'key1':'abc', 'key2':23, 'key3':(23, 24)} for k, v in var1.items(): print k, v print '\r\n'
结果1:
key3 (23, 24)
key2 23
key1 abc
代码2:
# 遍历列表 var2 = [1, 2, 3] for v in var2: print v
结果2:
1
2
3
代码3:
# 遍历元组 var3 = (1,2,3,4) for v in var3: print v
结果3:
1
2
3
4
代码4:
# 遍历字符串的每个字符 var4 = 'string' for c in var4: print c
结果4:
s
t
r
i
n
g
代码5:
# 对每个元素处理后生成新集合的写法 var5 = [v+1 for v in var3] print var5
结果5:
[2, 3, 4, 5]
代码6:
# 把集合var2的每个元素的值依次叠加到集合var3的每个元素的值上 var6 = [v1+v2 for v1 in var2 for v2 in var3] print var6 var7=[] for v1 in var2: for v2 in var3: var7.append(v1+v2) print var7
结果6:
[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7]
[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7]
代码6这个片段中,后面的嵌套循环等价于第一行的写法
代码7:
var8 = [(2,3,3), (5,6,6), (4,5,5)] for v1, v2, v3 in var8: print v1, v2, v3
结果7:
2 3 3
5 6 6
4 5 5
代码8:
var9 = (1, -2, 4, 5, -1) var10 = [v for v in var9 if v > 0] print var10
结果8:
[1, 4, 5]
这种方式实际上可以对集合中的元素进行条件过滤