[英]Understanding enumerate in python
I'm solving one python exercise and can't understand enumerate operation: Can anyone tell me how this will work: 我正在解决一个python练习,无法理解枚举操作:谁能告诉我这将如何工作:
>>> a = [[('A', {}), 1, None, None, 0], [('B', {}), 1, None, None, 0]]
>>> b = [('A', {}), ('B', {})]
>>> for each in b:
... my_idx = [idx for idx, val in enumerate(a) if a[idx][0] == each][0]
... print my_idx
...
and the output it produces is: 它产生的输出是:
0
1
To understand this, I did following changes: 为了理解这一点,我做了以下更改:
>>> a = [[('A', {}), 1, None, None, 0], [('B', {}), 1, None, None, 0], [('A', {}), 1, None, None, 0], [('B', {}), 1, None, None, 0]]
>>> b = [('A', {}), ('B', {}), ('A', {}), ('B', {})]
>>> for each in b:
... my_idx = [idx for idx, val in enumerate(a) if a[idx][0] == each][0]
... print my_idx
...
and thought it should print: 并认为它应该打印:
0
1
2
3
but it produced: 但产生了:
0
1
0
1
Where I'm going wrong? 我要去哪里错了? How should I modify it to produce:
我应该如何修改以产生:
0
1
2
3
Thanks. 谢谢。
To get the output you want you need to change your logic: 要获得所需的输出,您需要更改逻辑:
[idx for idx, val in enumerate(a) if any(val[0] == x for x in b)]
When printed outputs: 打印输出时:
print("\n".join([str(idx) for idx, val in enumerate(a) if any(val[0] == x for x in b)]))
0
1
2
3
You can also just test for membership using in
: 您也可以使用
in
测试会员资格:
print("\n".join([str(idx) for idx, val in enumerate(a) if val[0] in b]))
0
1
2
3
If val[0]
which corresponds to each tuple in the sublists of a
is in b
add the idx
which is the index of the element. 如果
val[0]
其对应于每个元组中的子列表a
是在b
添加idx
这是元素的索引。
You need to understand what enumerate
does. 您需要了解
enumerate
作用。 It is just a special function, which will give you number of evelemt in array you are using in for. 这只是一个特殊的功能,它将为您提供用于数组的elelemt数量。
for book in books:
print book
for author in authors:
print author
Will give you 会给你
Book A
Book B
Book C
Author A
Author B
Author C
But if you need to count it, to make a handy list with numbers, you can use enumerate
但是,如果您需要对其进行计数,以方便地列出数字,则可以使用
enumerate
for i, book in enumerate(books):
print i, book
for i, author in enumerate(authors):
print i, author
Will give you 会给你
1 Book A
2 Book B
3 Book C
1 Author A
2 Author B
3 Author C
This is what enumerate
does. 这就是
enumerate
。 It gives a nubmer to each element in array you are using. 它为您正在使用的数组中的每个元素提供了一个小数字。 Nothing more.
而已。 If you want to create global counter, you should consider using global variable.
如果要创建全局计数器,则应考虑使用全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.