使用枚举

时间:2018-05-02 05:37:29

标签: python enumerate

我知道enumerate的基本方式,但是当你在for循环中有两个变量时它会有什么不同?我在下面的示例中使用了counti

此代码:

Letters = ['a', 'b', 'c']
for count, i in enumerate(Letters):
    print(count, i)

和此:

Letters = ['a', 'b', 'c']
for i in enumerate(Letters):
    print(i)

两者都给出相同的输出,这个:

>>>
    0 'a'
    1 'b'
    2 'c'

在第一个例子的样式中编写代码在任何情况下都有益吗?有什么不同? 如果您知道任何其他可能有用的方法,请告诉我,我正在尝试扩展我在python中的知识

2 个答案:

答案 0 :(得分:5)

在第一个示例中,count设置为索引,i设置为元素。

在第二个示例中,i被设置为2元素元组(index,element)。

第一个例子相当于:

count, i = 0, 'a'

与:

相同
count = 0
i = 'a'

第二个例子与:

相同
i = (0, 'a')

答案 1 :(得分:1)

第一个给了你更多选择,比如:

Letters = ['a', 'b', 'c']
for count, i in enumerate(Letters):
    print(count, i.replace("a","t"))

如果您只想打印结果,第二个更简单