简体   繁体   English

了解python枚举

[英]Understanding pythons enumerate

I started to teach myself some c++ before moving to python and I am used to writing loops such as 在开始使用python之前,我开始自学一些c ++,而且我习惯于编写诸如

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

moving to python I frequently find myself using something like this. 转向python我经常发现自己正在使用类似这样的东西。

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? 我已经读到这根本不是“ pythonic”的,实际上我发现自己每次都要遍历东西时都使用这种类型的代码,我发现我应该使用的Python枚举函数,但是我不知道如何使用枚举来编写类似的代码? 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. 抱歉,如果这对于该论坛来说太基础了,请尝试绕开它,以便在学习时钻取“ pythonic”代码。

You don't need enumerate() at all in your example. 在您的示例中,您根本不需要enumerate()

Look at it this way: What are you using i for in this code? 这样看:您在代码中使用i做什么?

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? 您只需要它即可访问myList的各个成员,对吗? Well, that's something Python does for you automatically: 好吧,Python会自动为您执行以下操作:

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). 它基本上从C ++中抽象出您正在手工完成的所有计数工作,但它几乎完全相同(只在后台运行,因此您不必担心)。

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

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