Diego Mencos
Diego Mencos

Reputation: 33

how to know the index of a sublist with only one element

The issue is that I want to know the index of a sublist with only one element. For example:

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]

And I want to know the Index of the sublist where "CORA" appears.

Upvotes: 0

Views: 127

Answers (3)

Aaditya Ura
Aaditya Ura

Reputation: 12669

You can try enumerate , Just for fun you can play with lambda too.

print(list(filter(lambda x:x!=None,map(lambda x:list1.index(x) if 'CORA' in x else None ,list1))))

output:

[0, 1, 4, 5]

Upvotes: -1

Sphinx
Sphinx

Reputation: 10729

This is another idea to pull out the result you like.

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]
result = []
#print(list(result.append(index) or 'Processed' for index in range(0, len(list1))))
print(list(result.append(index) or 'Found' if list1[index][0] == 'CORA' else 'NotFound' for index in range(0, len(list1))))
print(result)

Output:

['Found', 'Found', 'NotFound', 'NotFound', 'Found', 'Found', 'NotFound']
[0, 1, 4, 5]
[Finished in 0.173s]

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can use enumerate:

list1=[('CORA', 'As'), ('CORA', '9'), ('DIA', 'K'), ('DIA', 'As'), ('CORA', 'J'), ('CORA', '6'), ('DIA', '7'),]
index = [i for i, [a, _] in enumerate(list1) if a == 'CORA']

Output:

[0, 1, 4, 5]

Upvotes: 3

Related Questions