Reputation: 1
I've a list of list and I need to get the index of that element in it.
Suppose I've a list [[0,0,0,'P'],[0,0,0,0],[0,'Q',0,0],[0,0,0,0]]
.
How can I get index of 'P'
and 'Q'
, if there's only one 'P'
and one 'Q'
?
I tried: list.index('P')
,
but got ValueError: 'P' is not in list
Upvotes: 0
Views: 123
Reputation: 71451
You can use list comprehension and enumerate
at each iteration:
l = [[0,0,0,'P'],[0,0,0,0],[0,'Q',0,0],[0,0,0,0]]
indexes = [[i for i, a in enumerate(b) if a == "P" or a == "Q"] for b in l]
You can also use a dictionary that stores the letter and a corresponding list with the sublist index and the letter index in the sublist:
new_dict = [{a:[i, b] for b, a in enumerate(c) if a == "P" or a == "Q"} for i, c in enumerate(l)]
new_dict = [i for i in new_dict if i]
final_dict = {**new_dict[0], **new_dict[1]}
print(final_dict)
Output:
{'Q': [2, 1], 'P': [0, 3]}
Finally, to get the complete sublists:
final_values = final_dict.values()
Output:
[[2, 1], [0, 3]]
Upvotes: 1
Reputation: 14141
You have to search in nested lists:
for nested_list in list:
if 'P' in nested_list:
index_of_P = nested_list.index('P')
break
The explanation:
index()
method raises the ValueError
when 'P'
is not found in nested_list
, hence the if
test just before its use.
As you have only one 'P'
, break
the for
loop after the successful search.
Note:
This is a simple but not recommended usage. After learning about the exceptions handling you will see more appropriate solution.
Upvotes: 0
Reputation: 1117
Here the elements of your search array are themselves arrays so you need to do some work to get what you want.
I will suppose that when searching for 'P' and 'Q' you are expecting to get a tuple as a result where the first value refers to the array where the search element appears and the second value refers to the index of the search element in the array where it appears.
You can write the following function
def find_position(array, elem):
for i, arr in enumerate(array):
if elem in arr:
return (i, arr.index(elem))
return (-1, -1) # elem do not exist
find_position(l, 'Q')
Out: (2, 1)
find_position(l, 'P')
Out (0, 3)
Upvotes: 0
Reputation: 607
If you are seeking the index at which the element is in the sublist, you can try this:
input_list = [[0,0,0,'P'],[0,0,0,0],[0,'Q',0,0],[0,0,0,0]]
def find_position(input_list, element):
index = 0
for sublist in input_list:
if element in sublist:
return index
index += 1
return None
find_position(input_list, 'P')
OUT: 0
find_position(input_list, 'Q')
OUT: 2
Upvotes: 0