1

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?

1 Answer 1

1

Simply you can use enumerate and list comprehension :

>>> [i for i,j in enumerate(L) if max(j)==j[0]]
[0, 2, 3, 5]
Sign up to request clarification or add additional context in comments.

4 Comments

Is that code all that's needed to render the correct output? When I runs it in the shell nothing happens. I forgot to say, I'm in Python 3.4
what you mean by nothing happens ?
I'm sorry, I'm not very good at this. It worked for me when I created a new list called L2 and added L2.append(i) in the beggining instead of just i. Maybe that's what you meant but as I said I'm kinda rubbish- Thank you so much!
your welcome ...! i thought you have omit something ! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.