Reputation: 107
I have a list containing sublists and the sublists contain other lists and tuples something like this
[[(1.0, 1.5), [2, 2], (1.5, 1.0)], [(1.1428571343421936, 0.28571426868438721), [1, 0], (0.5, 0.0)], [(0.66666668653488159, 0.0), [0, 0], [0, 1], (0.5, 1.25)]]
I want to search whether [2,2]
exists in a sublist or not and print the index of that sublist containing [2,2]
. For eg. the sublist containing [2,2]
is 0
.
I tried using the following code but it gives all the elements in an increasing fashion.
for index, value in enumerate(flat_list):
if value == [xpred,ypred]:
print(index)
Please suggest some alternative !!
Upvotes: 0
Views: 117
Reputation: 141
Here is some code that might help:
x = [[(1.0, 1.5), [2, 2], (1.5, 1.0)],
[(1.1428571343421936, 0.28571426868438721), [1, 0], (0.5, 0.0)],
[(0.66666668653488159, 0.0), [0, 0], [0, 1], (0.5, 1.25)]]
looking_for = [2,2]
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == looking_for:
print([i,j])
I have made a nested for loop. The outer loop iterates over all the items in the list x. These items are lists itself. The second for loop iterates within the sublists. Lastly, it is checked whether the tuple or list corresponds to what you are looking for and the indices of the ones that do are printed.
Hope this answers your question and good luck with you coding!
Upvotes: 1
Reputation: 3770
Try this
l = [[(1.0, 1.5), [2, 2], (1.5, 1.0)], [(1.1428571343421936, 0.28571426868438721), [1, 0], (0.5, 0.0)], [(0.66666668653488159, 0.0), [0, 0], [0, 1], (0.5, 1.25)]]
is_in_l = [l.index(pos) for pos in l if [2,2] in pos]
if is_in_l:
print('List Available at {} position'.format(is_in_l[0]))
else:
print('List not present')
Upvotes: 1