How do you know the index of an element that is in a sub list? A similar question was asked here for lists without nesting
Like so:
L=[[1, 2, 3], [4, 5, 6]]
What I want to be as output when the element is 3
:
output=[0][2]
L=[[1,2,3],[4,5,6],[2,3,4,5,3]]
a = 3
print([(i,j) for i,x in enumerate(L) if a in x for j,b in enumerate(x) if b == a])
#[(0, 2), (2, 1), (2, 4)]
using list comprehension you can dig and return all the sub values. If you need to go deeper just keep chaining the list comprehension or write a function to do it.
Try this:
def get_sublist_index(lists, item):
for sublist in lists:
if item in sublist:
return lists.index(sublist), sublist.index(item)
>>> L=[[1,2,3],[4,5,6]]
>>> get_sublist_index(L, 3)
(0, 2)
Or to get every item:
def get_sublist_index(lists, item):
for sublist in lists:
if item in sublist:
yield lists.index(sublist), sublist.index(item)
Making a generator:
>>> L=[[1,2,3],[4,3,6]]
>>> get_sublist_index(L, 3)
<generator object get_sublist_index at 0x1056c5e08>
>>> [i for i in get_sublist_index(L, 3)]
[(0, 2), (1, 1)]
Or if you don't want a generator:
def get_sublist_index(lists, item):
outList = []
for sublist in lists:
if item in sublist:
outList.append((lists.index(sublist), sublist.index(item)))
return outList
>>> get_sublist_index(L, 3)
[(0, 2), (1, 1)]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With