简体   繁体   中英

Python: Tie breaker when sorting a list of tuples (max for first element, and 1st occurrence of the second)

This is the list I started with

names = ["Alice", "Beatrice", "Amarnae", "Zootrope"]

The last three items all have 4 vowels each

Created a sorted list based on the count of vowels. Got the one shown below

mylist = [(3, 'Alice'), (4, 'Amarnae'), (4, 'Beatrice'), (4, 'Zootrope')]

I need to return/find the 1st occurrence of the max quantity

print(max(mylist))

which returns

(4, 'Zootrope')

Ask: I need to return as that is the first occurrence of the name in the original list

(4, 'Beatrice')

I have tried a few different things (incl. mylist.sort(key = lambda x: (x[0], x[1]) .. but doesn't seem to work.

Your mylist is not created with the original item order retained in the first place, hence the issue.

You can use a list comprehension like this to create mylist :

mylist = [(sum(c in 'aeiou' for c in name.lower()), name) for name in names]

which results in the following value for mylist , retaining the original item order:

[(3, 'Alice'), (4, 'Beatrice'), (4, 'Amarnae'), (4, 'Zootrope')]

Since max returns the first item with the maximum value, you can then simply use max with a key function that returns just the first item in the tuple for comparison, since you don't want the lexicographical order of the second item to be taken into account:

max(mylist, key=lambda t: t[0])

which returns:

(4, 'Beatrice')

Demo: https://replit.com/@blhsing/SwelteringFlakyDividend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM