Вопрос

I have a dictionary whose values are all lists of strings and I want to print the longest value(in this case, the list with the most strings). I created this for loop:

count=0
for values in d.values():
    if len(values)>count:
        count=len(values)
        print(values)

However, this prints all of the values ever associated with 'count'. I only want the largest one (which is the last line). This is an example of what the for loop prints:

['gul', 'lug']
['tawsed', 'wadset', 'wasted']
['lameness', 'maleness', 'maneless', 'nameless', 'salesmen']
['pores', 'poser', 'prose', 'repos', 'ropes', 'spore']
['arrest', 'rarest', 'raster', 'raters', 'starer', 'tarres', 'terras']
['carets', 'cartes', 'caster', 'caters', 'crates', 'reacts', 'recast', 'traces']
['estrin', 'inerts', 'insert', 'inters', 'niters', 'nitres', 'sinter', 'triens', 'trines']
['least', 'setal', 'slate', 'stale', 'steal', 'stela', 'taels', 'tales', 'teals', 'tesla'] 
['apers', 'apres', 'asper', 'pares', 'parse', 'pears', 'prase', 'presa', 'rapes', 'reaps', 'spare', 'spear']

How can I get it to print only that last(longest) line?

Это было полезно?

Решение 2

Inspired by Dilbert there is a chance for simplification, no need to use lambda to define function for comparing values, we may take advantage of the fact, that len returns length of each item and this is perfect key for deciding who comes first and who is last:

print sorted(d.values(), key=len)[-1]

Другие советы

max(d.values(), key=len)

This prints out the longest list of words from your dict values. I used the max() function, which takes a key parameter that is assigned to the function len(in this case). Basically, the criteria for which value is the 'max' value is now decided by it's len.

count = 0
for values in d.values():
    if len(values) > count:
        values_with_largest_count_first_hit = values
print(values_with_largest_count_first_hit)
print sorted(d.values(), cmp = lambda x, y: cmp(len(x), len(y)))[-1]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top