Reputation: 31
I'm trying to write a code that takes in a list with objects and next to the object there is also a number. I want to print the object which has the largest number next to it.
One idea is to look for the last value in the string by using the [-1]
, however I quickly realised that wouldnt work if the number was more than 1-digit.
I have also written this code, however this just returns the last element in the list.
list_of_words = ["car 1", "telephone 3", "bottle 10", "laptop 8", "window 12", "headphones 5"]
def autocomplete_freq_words():
for word in list_of_words:
return max(list_of_words)
print(autocomplete_freq_words())
Basically, for list_of_words and I want print the word "window".
Upvotes: 0
Views: 53
Reputation: 6234
You can use rsplit(maxsplit=1)
to split on whitespace and select the last element as your comparison key from each list element.
print(
max(list_of_words, key=lambda x: int(x.rsplit(maxsplit=1)[-1]))
)
Output:
window 12
Upvotes: 3
Reputation: 1788
You can sort your list and then take the last element
def autocomplete_freq_words(list_of_words):
list_of_words.sort(key=lambda w: int(w.split()[-1]))
return list_of_words[-1]
list_of_words = ["car 1","telephone 3","bottle 10", "laptop 8","window 12","headphones 5"]
print(autocomplete_freq_words(list_of_words))
Upvotes: 0