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

2019-09-19 12:03发布

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

4条回答
啃猪蹄的小仙女
2楼-- · 2019-09-19 12:43

You can do this using the standard heapq module:

>>> lst = ['hello', 'blah', 'boo', 'braininess']
>>> heapq.nlargest(2, lst, key=len)
['braininess', 'hello']
查看更多
家丑人穷心不美
3楼-- · 2019-09-19 12:43

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]. `

查看更多
forever°为你锁心
4楼-- · 2019-09-19 12:45

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']
查看更多
老娘就宠你
5楼-- · 2019-09-19 13:02
l = ['123', '12345', '12']
l.sort(key=lambda item: len(item))
l.[-1] # longest
l.[-2] # second longest
查看更多
登录 后发表回答