我目前正在通过Codecademy学习Python。其中一个练习在循环中使用了这个:
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index + 1, item
我只见过像:
for i in list:
话虽如此,我不明白"指数是什么,"循环的一部分是,或它的功能是什么。我从中理解的是它将索引列表中的每个项目并打印它们。提前谢谢。
答案 0 :(得分:3)
枚举产生list
tuple
(index, element)
。
l = ['thing', 'foo', 'bar', 'doodad']
list(enumerate(l))
这是enumerate
[(0, 'thing'), (1, 'foo'), (2, 'bar'), (3, 'doodad')]
你可以unpack
这些元组,并对元组的每个组件做任何你想做的事。
for index, element in enumerate(l):
print 'index', index
print 'element', element
index 0
element thing
index 1
element foo
index 2
element bar
index 3
element doodad
答案 1 :(得分:2)
enumerate
返回列表中项目的索引和项目本身。 Python列表中的每个项目(以及几乎任何编程语言中的任何列表)除了包含它的值之外还有一个数字索引。在Python中,索引从0开始。因此,对于choices
列表,pizza
的索引为0
,pasta
为1
,salad
为2
,nachos
有3
。此索引的存在是为了允许您直接访问列表的第n个值,而不必循环访问它(以及其他用途)。
以下是您的代码在执行时所执行的操作:
Your choices are:
1 pizza # Pizza has index 0, and you added 1
2 pasta # Index 1
3 salad # Index 2
4 nachos # Index 3
答案 2 :(得分:0)
enumerate
为从0开始的列表中的每个项目添加索引或位置值。
因此,在您的示例中,pizza
的索引为0,pasta
的索引为1,依此类推......
然后,您的for
语法略有不同,以获取当前项的索引和值。
因此,首次完成循环后,您将获得index = 0
和item = 'pizza'
答案 3 :(得分:0)
它来自enumerate
内置函数,如枚举文档中所述:python 2 documentation,python 3 documentation。我认为文档非常清楚地描述了它,所以建议在那里阅读。