可能重复:
列表中最长的字符串
lst = [str1, str2, str3, ...]
max(lst, key=len)
这仅返回具有最大长度的字符串之一。有没有办法在不定义另一个程序的情况下做到这一点?
怎么样:
maxlen = len(max(l, key=len))
maxlist = [s for s in l if len(s) == maxlen]
如果要获取最大长度的所有值,则可能需要按长度对列表进行排序;那么您只需要获取所有值,直到长度发生变化。itertools
提供了多种方法来做到这一点——<code>takewhile,groupby
等。例如:
>>> l = ['abc', 'd', 'ef', 'ghi', 'j']
>>> l2 = sorted(l, key=len, reverse=True)
>>> groups = itertools.groupby(len, l2)
>>> maxlen, maxvalues = next(groups)
>>> print(maxlen, list(maxvalues))
3, ['abc', 'ghi']
如果你想要一个单行:
>>> maxlen, maxvalues = next(itertools.groupby(len, sorted(l, key=len, reverse=True)))
>>> print(maxlen, list(maxvalues))
当然,如果您愿意,您总是可以只遍历列表两次——首先找到最大长度,然后找到所有匹配值:
>>> maxlen = len(max(l, key=len))
>>> maxvalues = (value for value in l if len(value) == maxlen)
>>> print(maxlen, list(maxvalues))
只是为了完整起见,filter
也是一种选择:
maxlens = filter(lambda s: len(s)==max(myList, key=len), myList)
这是一个一次性解决方案,收集迄今为止发现的最长的单词。
def findLongest(words):
if not words:
return []
worditer = iter(words)
ret = [next(worditer)]
cur_len = len(ret[0])
for wd in worditer:
len_wd = len(wd)
if len_wd > cur_len:
ret = [wd]
cur_len = len_wd
else:
if len_wd == cur_len:
ret.append(wd)
return ret
以下是一些测试列表的结果:
tests = [
[],
"Four score and seven years ago".split(),
"To be or not to be".split(),
"Now is the winter of our discontent made glorious summer by this sun of York".split(),
]
for test in tests:
print test
print findLongest(test)
print
[]
[]
['Four', 'score', 'and', 'seven', 'years', 'ago']
['score', 'seven', 'years']
['To', 'be', 'or', 'not', 'to', 'be']
['not']
['Now', 'is', 'the', 'winter', 'of', 'our', 'discontent', 'made', 'glorious', 'summer', 'by', 'this', 'sun', 'of', 'York']
['discontent']