Find the two longest strings from a list || or the second longest list in PYTHON

余生颓废 提交于 2019-12-13 08:37:59

问题


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


来源:https://stackoverflow.com/questions/9887374/find-the-two-longest-strings-from-a-list-or-the-second-longest-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!