简体   繁体   中英

Understanding pythons enumerate

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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