Understanding pythons enumerate

倖福魔咒の 提交于 2019-12-02 04:21:33

In general, this is sufficient:

for item in myList:
    if item == something:
        doStuff(item)

If you need indices:

for index, item in enumerate(myList):
    if item == something:
        doStuff(index, item)

It does not do anything in parallel. It basically abstracts away all the counting stuff you're doing by hand in C++, but it does pretty much exactly the same thing (only behind the scenes so you don't have to worry about it).

You don't need enumerate() at all in your example.

Look at it this way: What are you using i for in this code?

i = 0
while i < len(myList):
   if myList[i] == something:
       do stuff
   i = i + 1 

You only need it to access the individual members of myList, right? Well, that's something Python does for you automatically:

for item in myList:
    if item == something:
        do stuff
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!