Find the two longest strings from a list || or the

2019-09-19 12:54发布

问题:

I'd like to know how i can find the two longest strings from a list(array) of strings or how to find the second longest string from a list. thanks

回答1:

You can do this using the standard heapq module:

>>> lst = ['hello', 'blah', 'boo', 'braininess']
>>> heapq.nlargest(2, lst, key=len)
['braininess', 'hello']


回答2:

Easiest way to do this is use the sorted() function by using another built-in function len as the key argument as follows;

>>> foo = ['dddd', 'ccc', 'bb', 'a', 'eeeee']
>>> sorted(foo, key=len)[-2]
'dddd'

or if you need the two longest:

>>> sorted(foo, key=len)[-2:]
['dddd', 'eeeee']


回答3:

If a is your list of strings, then a.sort(key=len) will sort your list of strings by their length. The longest would be a[-1], and the second longest would be a[-2]. `



回答4:

l = ['123', '12345', '12']
l.sort(key=lambda item: len(item))
l.[-1] # longest
l.[-2] # second longest