finding all the indices of with a value in a list of lists
Question:
I am trying to find all the indices that have the same values in a list.
but in my list, there are lists inside the list and I don’t know how to do it
I found how to do that for a normal list:
list=[2,5,9,1,3,1]
list.index(1)
it will print the indices of value
1: [3,5]
but for this list:
list=[1, [2,3,17] , 3 , [0,1,2,7,3] , 2 ]
for the value 2
it will need to print: [[1, 0], [3, 2], [4]]
but I don’t know how to do that for this kind of list.
Answers:
Firstly, don’t name any variables list
in python — it is already a function.
To answer the question, you can loop through the list and use recursion each time there is a list inside of the list:
def getNestedIdxs(l, num): # l is the list and num is what we are looking for
result = []
for idx, element in enumerate(l):
if element == num: result.append([idx])
elif isinstance(element, list): # This checks if the element is a list
result.extend([[idx] + elem for elem in getNestedIdxs(element, num)])
return result
print(getNestedIdxs([[[1, 2, 3,[0,1,2]], 2, [1, 3]], [1, 2, 3]], 2))
I am trying to find all the indices that have the same values in a list.
but in my list, there are lists inside the list and I don’t know how to do it
I found how to do that for a normal list:
list=[2,5,9,1,3,1]
list.index(1)
it will print the indices of value
1: [3,5]
but for this list:
list=[1, [2,3,17] , 3 , [0,1,2,7,3] , 2 ]
for the value 2
it will need to print: [[1, 0], [3, 2], [4]]
but I don’t know how to do that for this kind of list.
Firstly, don’t name any variables list
in python — it is already a function.
To answer the question, you can loop through the list and use recursion each time there is a list inside of the list:
def getNestedIdxs(l, num): # l is the list and num is what we are looking for
result = []
for idx, element in enumerate(l):
if element == num: result.append([idx])
elif isinstance(element, list): # This checks if the element is a list
result.extend([[idx] + elem for elem in getNestedIdxs(element, num)])
return result
print(getNestedIdxs([[[1, 2, 3,[0,1,2]], 2, [1, 3]], [1, 2, 3]], 2))