Understanding pythons enumerate

扶醉桌前 提交于 2020-01-11 12:13:08

问题


I started to teach myself some c++ before moving to python and I am used to writing loops such as

   for( int i = 0; i < 20; i++ )
   {
       cout << "value of i: " << i << endl;
   }

moving to python I frequently find myself using something like this.

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

I have read that this isnt very "pythonic" at all , and I actually find myself using this type of code alot whenever I have to iterate over stuff , I found the enumerate function in Python that I think I am supposed to use but I am not sure how I can write similar code using enumerate instead? Another question I wanted to ask was when using enumerate does it effectively operate in the same way or does it do comparisons in parallel?

In my example code:

if myList[i] == something:

With enumerate will this check all values at the same time or still loop through one by one?

Sorry if this is too basic for the forum , just trying to wrap my head around it so I can drill "pythonic" code while learning.


回答1:


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).




回答2:


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


来源:https://stackoverflow.com/questions/29619801/understanding-pythons-enumerate

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