PandaDeTapas
PandaDeTapas

Reputation: 516

Using list.index with duplicate items inside the list in Python

I'm working in python 3.4

I have a problem with a piece in a program that is supposed to return all nested lists which first value is the biggest value.

I first tried the following code:

L = [['5','4','3'], ['23', '40', '8'], ['33', '24', '29'], ['33', '24', '29'],
 ['13', '66', '54'], ['5', '4', '3']]

BigNumFirst = []
for i in L:
if i[0] > i[1] and i[0] > i[2]:
    BigNumFirst.append(L.index(i))
print(BigNumFirst)

And got the following output:

[0, 2, 2, 0]

As you can see the problem is that list.index() only returns the first matching nested list, so the index for the duplicate nested lists is not correct. I want the output to be:

[0, 2, 3, 5]

I can't figure out how I should solve this, at first I thought I could just add a variable that kept count of how many of a duplicate that existed inside of

BigNumFirst

but that of course only works if there's only one nested list with duplicates as my attempt showed:

BigNumFirst = []
NumbOfCopys=0
for i in L:
if i[0] > i[1] and i[0] > i[2]:
    if L.index(i) in BigNumFirst:
        NumbOfCopys+=1
    BigNumFirst.append(L.index(i)+NumbOfCopys)

print(BigNumFirst)

output:

[0, 2, 3, 2]

As you can see the last number is still wrong. So, how would I do to make my program "know" what index a nested list has, even if it is a duplicate of a previous nested list?

Upvotes: 1

Views: 184

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

Simply you can use enumerate and list comprehension :

>>> [i for i,j in enumerate(L) if max(j)==j[0]]
[0, 2, 3, 5]

Upvotes: 1

Related Questions