enumerate函數(shù):遍歷一個(gè)序列的同時(shí)追蹤當(dāng)前元素的索引。
some_list=['foo','bar','baz']
mapping={}
for i,value in enumerate(some_list):
mapping[value]=i
print(mapping)
結(jié)果顯示:
{‘foo’: 0, ‘bar’: 1, ‘baz’: 2}
Process finished with exit code 0
# zip 將列表,元祖或其他序列的元素配對,新建一個(gè)元祖構(gòu)成的列表
seq1=['foo','bar','baz']
seq2=['one','two','three']
zipped=zip(seq1,seq2)
print(list(zipped))
# zip可以處理任意長度的序列,它生成列表長度由最短的序列決定
seq3=['False','True']
print(list(zip(seq1,seq2,seq3)))
結(jié)果顯示
[(‘foo’, ‘one’), (‘bar’, ‘two’), (‘baz’, ‘three’)]
[(‘foo’, ‘one’, ‘False’), (‘bar’, ‘two’, ‘True’)]
Process finished with exit code 0
一般來說,enumerate和zip函數(shù)是一起用的,他們的應(yīng)用場景
zip的常用場景為同時(shí)遍歷多個(gè)列表,有時(shí)候會(huì)和enumerate同時(shí)使用
seq1=['foo','bar','baz']
seq2=['one','two','three']
for i,(a,b) in enumerate(zip(seq1,seq2)):
print('{}:({},{})'.format(i,a,b))
結(jié)果顯示
0:(foo,one)
1:(bar,two)
2:(baz,three)
Process finished with exit code 0
|