简体   繁体   English

如何使用枚举在python中的for循环中使用多个变量?

[英]How multiple variables work in for loop in python with enumerate?

I wanted to access the index of each element of iterable object. 我想访问可迭代对象的每个元素的索引。 I found out on the internet that one can use enumerate function to generate tuples having index associated with respective element. 我在互联网上发现可以使用枚举函数生成具有与各个元素相关联的索引的元组。 But I have one confusion, how does python know which of the variables I chose in for loop is assigned the index and which variable is assigned the actual value of element? 但是我有一个困惑,python如何知道我在for循环中选择的哪个变量被分配了索引,哪个变量被分配了element的实际值?

I understand that this is not a problem just with enumerate function. 我知道,这仅与枚举函数无关。 Its a thing associated with for loop itself and I want to understand how it works. 它与for循环本身有关,我想了解它是如何工作的。 Here's an example: 这是一个例子:

for idx, val in enumerate(items):
    print("index is:"+str(idx)+" and value is:"+str(val))

How does python decide that "idx" gets the value of index of the two parts in tuple element and "val" gets the actual value part? python如何确定“ idx”获取元组元素中两个部分的索引值,而“ val”获取实际值部分?

Is it something like the one on the left in "var1,var2" gets the index? 是否类似于“ var1,var2”左侧的那个获取索引?

Can we make it so that "val" gets the index and "idx" gets the actual value without changing their order of appearance in " for idx,val in enumerate(items)" 我们可以做到这一点,以使“ val”获得索引,“ idx”获得实际值,而无需更改“对于idx,enumerate(items)中的val”的出现顺序

Its tuple unpacking, the basic form is: 它的元组解包,基本形式是:

x, y = 2, 3
print(x, y) # Prints: 2 3

The enumerate call just returns the index as the first element and the value as the second: enumerate调用仅将索引作为第一个元素,将值作为第二个返回:

a = ['a', 'b', 'c']
for index, val in enumerate(a):
    print(index, val) # Outputs 0 a --> 1 b --> 2 c

The naming is arbitrary: 命名是任意的:

a = ['a', 'b', 'c']
for b, c in enumerate(a):
    print(b, c) # Outputs 0 a --> 1 b --> 2 c

You can see this also with: 您还可以通过以下方式查看此内容:

a = ['a', 'b', 'c']
for tup in enumerate(a):
    print(tup) # Outputs: (0, a) --> (1, b) --> (2, c)

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

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