python - How to get list of indexes of all occurences of the same value in list of lists? -


having list of lists,

mylist = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3]] 

i need method list containing indexes of elements of value, '3' example. value of '3' such list of indexes should be

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

thanks in advance.

update: can have several instances of sought-for value ('3' in our case) in same sublist, like

my_list = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3, 3]] 

so desired output [[0, 1], [1, 0], [2, 3], [2, 4]].

i suppose solution naive, here is:

my_list = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3, 3]] value = 3 list_of_indexes = []  in range(len(my_list)):         j in range(len(my_list[i])):             if my_list[i][j] == value:                 index = i, j                 list_of_indexes.append(index)  print list_of_indexes  >>[(0, 1), (1, 0), (2, 3), (2, 4)]] 

it great see more compact solution

assuming value appears once in each sublist, use following function, makes use of built in enumerate function , list comprehension:

my_list = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3]]  def func(my_list, x):     return [[idx, sublist.index(x)] idx, sublist in enumerate(my_list)]  answer = func(my_list, 3) print(answer) 

output

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

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -