I have a list with sub-lists: and I want to have the index from the sub-list where on the 0 place a name is stored: So in the following list I want to find the index of sub-list where 'Kolom3' is in
[['Kolom1', 'Tekst'], ['Kolom2', 'Tekst'], ['Kolom3', 'Tekst']]
so it must something do with list.index('Kolom3')
and must return 3 and preferably not a for loop
CodePudding user response:
You can do that with zip
though the output is 2
as Python uses 0 indexing:
list(list(zip(*lst))[0]).index('Kolom3')
Output:
2
CodePudding user response:
Considering the list to be as:
A = [['Kolom1', 'Tekst'], ['Kolom2', 'Tekst'], ['Kolom3', 'Tekst']]
Method 1:
This method uses a traditional for loop to figure out the index
for i, val in enumerate(A, 1):
if "Kolom3" in val:
print(f"Kolom3 is in position {i}")
Method 2:
This method directly references ["Kolom3", 'Tekst']
.
The caveat here, is - what about duplicates?
What if the second element is changed from Tekst
to something else?
print(A.index(["Kolom3", 'Tekst']) 1)
Method 3:
This method uses list comprehension.
index = [i 1 for i, val in enumerate(A) if "Kolom3" in val]
print(index)
CodePudding user response:
You can use itertools.dropwhile
:
>>> import itertools
>>> L = [['Kolom1', 'Tekst'], ['Kolom2', 'Tekst'], ['Kolom3', 'Tekst']]
>>> dw = itertools.dropwhile(lambda i: L[i][0] != 'Kolom3', range(len(L)))
>>> ind = next(dw) 1
>>> ind
3
Basically go over the range of indices and return the first index whose value verifies the condition.