As a continuation for this question , how can I get the index of the sublist which contains the element?
So for example if I have:
a = [[1,2],[3,4],[5,6]]
any(2 in i for i in a)
....
How can I get 0 as a result (Because a[0] contains the number 2)?
Alternatively, you can try this too:
for idx, sublst in enumerate(a):
if 2 in sublst:
print(idx)
Output:
0
Simple list comprehension which iterates over list with indexes using enumerate()
will do the trick:
res = [i for i, el in enumerate(a) if 2 in el]
You can achieve same using regular for loop:
res = []
for i, el in enumerate(a):
if 2 in el:
res.append(el)
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.