How to Locate the Index With in a Nested List Python

Finding the index of an element in nested lists in python

def find_in_list_of_list(mylist, char):
for sub_list in mylist:
if char in sub_list:
return (mylist.index(sub_list), sub_list.index(char))
raise ValueError("'{char}' is not in list".format(char = char))

example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]

find_in_list_of_list(example_list, 'b')
(0, 1)

How To find position of nested list in list in python

x=[12.011, [1.007, 2, 15.999], 4]

for i in x:
if type(i) == list:
print(x.index(i))

This will help you.

x=[12.011, [1.007, 2, 15.999], 4, [1, 2]]

y = list(i for i, j in enumerate(x) if type(j) == list)
print(y)

This will make a list of indices.

How to find index of a given value in a nested list in Python?

Everything seems fine in your code, just make the string formatter a tuple. Modify the last line of your code to this below:

print('the index of 1 is [%d][%d] ' % (item,item2))

How can I get the index of a nested list item?

Try this:

[(i, el.index("plum")) for i, el in enumerate(some_list) if "plum" in el]

Output:

[(1, 1)]

Finding index in nested list

As @tzaman mentioned, you need to handle the return value of find_item recursive call. If the return value of the recursive call is a list, it will mean that searched item is found and we need to stop the recursion.

The following modification will return the earliest found index of the searched item. If no item is found, it will return None.

def find_item(list_input, item, current):
if list_input == item:
return current
else:
if isinstance(list_input, list):
for j in range(len(list_input)):
current.append(j)
search_result = find_item(list_input[j], item, current)
if isinstance(search_result, list):
return search_result
del current[-1]

list_input = [0, 5, [6, 8, [7, 3, 6]], 9, 10]
item = 7
print(find_item(list_input, item, []))

list_input = [0, 5, [6, 8, [7, 3, 6]], 9, 10]
item = 9
print(find_item(list_input, item, []))

list_input = [0, 5, [6, 8, [7, 3, 6]], [30, 4], 9, 10]
item = 4
print(find_item(list_input, item, []))

list_input = [0, 5, [6, 8, [7, 3, 6]], [30, 4], 9, 10]
item = 400
print(find_item(list_input, item, []))

Output:

[2, 2, 0]
[3]
[3, 1]
None

Index of an element in a nested list

Ajax1234's answer works, but if you need something a little more simple this may be better:

def find_idx(input_list, elem):
for i in range(len(input_list)):
if isinstance(input_list[i], list):
result = find_idx(input_list[i], elem)
if result:
return [i] + result
elif input_list[i] == elem:
return [i]

return False

input_list = [1, [5, 62, 6], 4, [99, [100, 200, 600, [1000, [2000]]]], [74, 41, 16], 7, [8], [[[400]]]]

print(find_idx(input_list, 2000))
# Output: [3, 1, 3, 1, 0]


This is basically a DFS (https://en.wikipedia.org/wiki/Depth-first_search). If you think of your data structure as a tree, your list entries are nodes since they themselves can contain other lists, just as a node in a tree can point to other nodes. The magic is in returning False if nothing was found at the very end of the method, but recursively searching all sublists before you get to that point. Also, you have to check whether your list entry is itself a list, but this is just an analogy to the fact that a tree can have nodes that do point to other nodes, and nodes that do not (leaf nodes, or plain old numbers in your case).

How to locate the index with in a nested list Python

You can also make good use of enumerate. First find the row (with its index) with the maximum number. Then find that number and its index in that row.

In both cases you need to provide a key to the max function so that it considers the value (not the index):

def find_peak(m):
i, max_row = max(enumerate(m), key=lambda x: max(x[1]))
j, max_val = max(enumerate(max_row), key=lambda x: x[1])
return [i, j]

Output

print(find_peak([[1,2,3], [9,8,7], [5,4,6]]))
# [1, 0]
print(find_peak([[6,2,3], [1,8,7], [5,4,9]]))
# [2, 2]

finding the index of elements in nested list

A nested comprehension using enumerate will do:

table = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]

def coordinates(tbl):
return [(i, j) for i, row in enumerate(tbl) for j, _ in enumerate(row)]
# or a little shorter
# [(i, j) for i, row in enumerate(tbl) for j in range(len(row))]

coordinates(table)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Your list.index(elmnt) based approach fails because index always returns the first index of the element in the list, so it won't work if there are repetitions. Also, it has worse performance since every index call must iterate the list it is called on.
A pure loop-index-based implementation along your original lines would be:

def coordinates(tbl):
target_cell_list = []
for i in range(len(tbl)):
for j in range(len(tbl[i])):
target_cell_list.append((i, j))
return target_cell_list

And if you know that your table is not jagged, you can use itertools.product:

from itertools import product

def coordinates(tbl):
return list(product(range(len(tbl)), range(len(tbl[0]))))


Related Topics



Leave a reply



Submit