简体   繁体   English

Python:枚举

[英]Python: Enumeration

People have said that the enumerate function is a hidden trick in python. 人们曾经说过,枚举函数是python中的一个隐藏技巧。 I am still unsure as to what it does. 我仍然不确定它的作用。 The documentation just tells me that it returns an enumerate object. 该文档只是告诉我它返回一个枚举对象。 That doesn't exactly help me in understanding this concept. 那并不能完全帮助我理解这个概念。

What does enumeration do? 枚举是做什么的?

Enumerate pairs the index of each element with the element: 枚举将每个元素的索引与元素配对:

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

(0, 'a')
(1, 'b')
(2, 'c')

In addition, you can create your own enumeration by yourself: 另外,您可以自己创建自己的枚举:

enum = lambda l: zip([i for i in range(len(l))], l)

enumerate() can be used with any iterable. enumerate()可以与任何迭代器一起使用。 It enumerates the values returned by the iterable. 它枚举了iterable返回的值。

3>> enumerate(['a', 'b', 'c'])
<enumerate object at 0x7f1340c44a50>
3>> list(enumerate(['a', 'b', 'c']))
[(0, 'a'), (1, 'b'), (2, 'c')]
3>> list(enumerate({'a', 'b', 'c'}))
[(0, 'c'), (1, 'b'), (2, 'a')]
3>> list(enumerate({'a':0, 'b':0, 'c':0}))
[(0, 'c'), (1, 'b'), (2, 'a')]

Note that the set and dict results are not in error; 请注意, setdict结果没有错误; they are arbitrarily ordered, hence do not necessarily "come out" the same way they "go in". 它们是任意排序的,因此不一定像“进入”一样“出来”。 And as always, iterating over a mapping yields its keys. 与往常一样,遍历映射会产生其密钥。

enumerate() is a fancy tool that gives you the index of the item in the iterable as well as the item. enumerate()是一个精美的工具,可为您提供该项目在可迭代项目以及项目中的索引。 There is nothing you can't do with you standard for loop. 没有什么是您无法使用的标准循环。

lets say we have this simple list. 可以说我们有这个简单的清单。 lst = ['red', 'car', 'machine', 'go', 'cloud', 'cabbages']

An example of enumerate() enumerate()的示例

for index, item in enumerate(lst):
    print(str(item) + " Is item number: " + str(index))

without enumerate() this could might look like. 如果没有enumerate() ,则可能看起来像。

for count in range(len(lst)):
    print(str(lst[count]) + " Is item number: " + str(count))

Both produce the same output. 两者产生相同的输出。

>>> red Is item number: 0
>>> car Is item number: 1
>>> machine Is item number: 2
>>> go Is item number: 3
>>> cloud Is item number: 4
>>> cabbages Is item number: 5

When iterating ( for ) enumerate object it returns position and thing which would usually be returned: 迭代( for )枚举对象时,它返回通常会返回的位置和东西:

a = ["a", "b", "c"]
for pos, x in enumerate(a):
    print(pos, x)

Example above should be used instead of: 应使用上面的示例代替:

a = ["a", "b", "c"]
for x in range(len(a)):
    print(x, a[x])

because of code clarity. 因为代码清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM