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