时间:2021-07-01 10:21:17 帮助过:37人阅读
比如我们有一个["one","two","there"]的列表,我们需要在列表的每个元素前面加上他的编号
代码如下:
i = 0
seq = ["one","two","three"]
for element in seq:
seq[i] = '%d: %s' % (i, seq[i])
i += 1
print seq
['0: one', '1: two', '2: three']
使用enumerate函数,我们可以简化我们的代码,省去定义计数用的临时变量
代码如下:
seq = ["one","two","three"]
for i, element in enumerate(seq):
seq[i] = '%d: %s' % (i, seq[i])
print seq
['0: one', '1: two', '2: three']
代码如下:
seq = ["one","two","three"]
print ['%d: %s'% (i,element) for i,element in enumerate(seq) ]
['0: one', '1: two', '2: three']