I am new to this and I would to find specifc index of item from lists in list in Python. It only work with multiple lists in one list, and I would to know if you know much simple way to search trought all existing and new added list to find specific index of an item and more than in two lists. I would be greatful for help.
JavaScript
x
49
49
1
main_list = [[0, 1, 1, 3], [1, 'b', 'c', 'd'], [0, 'b', 1, 'd']]
2
3
print(f'MAIN LIST: {main_list}')
4
5
find_in_list = False # put number of list if specific search is needed ### find_in_list = 1
6
find_item = 'b' # item that you want to find in one or multiple lists
7
8
count_number_of_lists = -1
9
10
add_item_index = []
11
store_items_index = []
12
item_index_of_store_items_index = 0
13
list_index_and_item_index = []
14
15
for sub_list_index, sub_list_others in enumerate(main_list):
16
17
count_number_of_lists += 1
18
19
if find_in_list == False:
20
sub_list = main_list[sub_list_index] # no specific list
21
22
for sub_list_index_2, sub_list_others_2 in enumerate(sub_list):
23
if sub_list_others_2 == find_item: # find exactly same item as needed to be found
24
add_item_index.append(sub_list_index_2)
25
print(add_item_index)
26
27
else:
28
sub_list = main_list[find_in_list] # specific list
29
30
for sub_list_index_2, sub_list_others_2 in enumerate(sub_list):
31
if sub_list_others_2 == find_item: # find exactly same item as needed to be found
32
add_item_index.append(sub_list_index_2)
33
34
store_items_index.append(add_item_index)
35
add_item_index = []
36
for sub_index, sub_other in enumerate(store_items_index):
37
item_index_of_store_items_index = store_items_index[sub_index]
38
39
list_index_and_item_index.append([count_number_of_lists, item_index_of_store_items_index])
40
if find_in_list == False:
41
print(f'LIST INDEX: {count_number_of_lists}, ITEM INDEX: {item_index_of_store_items_index}')
42
43
if find_in_list == False:
44
print(f'List of [LIST INDEX and, [ITEM INDEX]]: {list_index_and_item_index}') # all LIST INDEX and ITEM INDEX in one list
45
print(f'ALL ITEMS INDEX: {store_items_index}') # all index of items in one list
46
47
else:
48
print(f'LIST INDEX: {count_number_of_lists}, ITEM INDEX: {item_index_of_store_items_index}')
49
Advertisement
Answer
JavaScript
1
19
19
1
main_list = [[0, 1, 1, 3], [1, 'b', 'c', 'd'], [0, 'b', 1, 'd']]
2
3
find_in_list = False
4
find_item = 'b'
5
6
if not find_in_list:
7
list_indices = list(range(len(main_list)))
8
else:
9
list_indices = [find_in_list]
10
11
res = []
12
for i in list_indices:
13
occurrences = []
14
for j, e in enumerate(main_list[i]):
15
if e == find_item:
16
occurrences.append(j)
17
res.append([i, occurrences])
18
print(res)
19
prints
JavaScript
1
2
1
[[0, []], [1, [1]], [2, [1]]]
2