内置函数 | |
range() | 返回一系列连续增加或减小的整数 |
zip() | 返回一系列并行元素的元组,可用于在for中遍历多个序列 |
enumerate() | 同时生成可迭代对象中元素的值和索引,返回一系列(index, value)元组 |
range()
返回一系列连续增加或减小的整数
生成数字列表
list(range(5))
[0, 1, 2, 3, 4]
指定具体循环重复次数
for i in range(3):
print(i)
使用range()和len(),作为序列容器的索引,对容器进行操作
L = [1, 2, 3]
for i in range(len(L)):
X = L[i:] + L[:i]
print(X, end=' ')
output:
[1, 2, 3] [2, 3, 1] [3, 1, 2]
zip()
内置的zip函数允许我们使用for循环并行访问多个序列
zip的输入参数是一个或多个序列,由这些序列并排的元素可以配对成一个元组
zip的返回值是可迭代对象,可以迭代返回这些元组
生成配对元组列表
L1 = [1, 2, 3, 4]
L2 = [5, 6, 7, 8]
list(zip(L1, L2))
output:
[(1, 5), (2, 6), (3, 7), (4, 8)]
与for循环配合使用时,它就能支持并行迭代
for x, y in zip(L1, L2):
print(x, y)
output:
1 5
2 6
3 7
4 8
当各个参数长度不等时,zip会以最短序列的长度为准来截断结果元组
S1 = 'abc'
S2 = 'xyz123'
list(zip(S1, S2))
output:
[('a', 'x'), ('b', 'y'), ('c', 'z')]
构造字典
keys = ['spam', 'eggs', 'toast']
vals = [1, 3, 5]
dict(zip(keys, vals))
output:
{'spam': 1, 'eggs': 3, 'toast': 5}
enumerate()
同时生成可迭代对象中元素的值和索引,返回一系列 (index, value) 元组
S = 'spam'
for offset, item in enumerate(S):
print(offset, item)
output:
0 s
1 p
2 a
3 m