Reputation: 133
I have a nested loop. I want to iterate on a list of lists and check if a parameter is in a list, bring me back the list index.
parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]
for i in Li:
for j in i:
if (parameter==j):
x=i+1
print(x)
I expect an integer like for this example x=2. But it does not work. How can I do that?
Upvotes: 0
Views: 1395
Reputation: 19
parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]
index = -1
for i in Li:
if parameter in i:
index = Li.index(i)
print(index)
You can check if something is in a list with 'in' and get the index of the element with .index, it returns the integer position in the list.
Perhaps you want a tuple for the nested position ?
use something like (Li.index(i), i.index(parameter))
as your return value.
Don't forget to declare your return value outside your loop scope !
Upvotes: 0
Reputation:
Use numpy
array. It will save you tons of time and cost.
Li = np.array([li1,li2])
Li == parameter
array([[False, False],
[ True, False]])
row, column = np.where(Li == parameter)
row
Out[17]: array([1], dtype=int64)
Upvotes: 0
Reputation: 214
You didn't specify the output you are expecting, but I think you want something like this:
parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]
for row in Li:
for i, j in enumerate(row):
if parameter == j:
print("List", Li.index(row),"Element", i)
Output:
List 1 Element 0
Upvotes: 1
Reputation: 12347
Use enumerate
, which returns the index and the element. Also use sets, which are faster than lists (for long lists).
parameter = "Abcd"
lst1 = ["ndc", "chic"]
lst2 = ["Abcd", "cuisck"]
lst = [lst1, lst2]
x = None
for i, sublst in enumerate(lst):
if parameter in set(sublst):
x = i+1
print(x)
# 2
Upvotes: 0