标签:
#切片 L = [‘Michael‘, ‘Sarah‘, ‘Tracy‘, ‘Bob‘, ‘Jack‘] print(L[0:3]) print(L[:3]) print(L[1:3]) print(L[:10:2]) print(L[::5]) print(L[:]) #复制一个list print((0, 1, 2, 3, 4, 5)[:3]) print(‘ABCDEFG‘[:3])
from collections import Iterable d = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3} for key in d: print(key) for value in d.values(): print(value) for k, v in d.items(): print(k, v) for ch in ‘ABC‘: print(ch) # 是否可迭代 print(isinstance(123, Iterable)) #Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身 for i, value in enumerate([‘A‘, ‘B‘, ‘C‘]): print(i, value) for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y)
print(list(range(1, 11))) L = [] for v in list(range(1, 11)): L.append(v * v) print(L) #写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来 print([x * x for x in range(1, 11)]) print([x * x for x in range(1, 11) if x % 2 == 0]) print([m + n for m in ‘ABC‘ for n in ‘XYZ‘]) d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ } print([k + ‘=‘ + v for k, v in d.items()]) L = [‘Hello‘, ‘World‘, ‘IBM‘, ‘Apple‘] print([s.lower() for s in L])
标签:
原文地址:http://www.cnblogs.com/jzm17173/p/4998494.html