I'm solving one python exercise and can't understand enumerate operation: Can anyone tell me how this will work:
>>> 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
:
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.
You need to understand what enumerate
does. It is just a special function, which will give you number of evelemt in array you are using in for.
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
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. 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.
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.