您可以改用排序:
maxed = sorted(inputlist, key=lambda i: len(i), reverse=True)
allmax = list(takewhile(lambda e: len(e) == len(maxed[0]), maxed))
排序需要O(n log n)
时间;但它既简单又简短,因为最长的元素都在开头以便于挑选。
对于O(n)
解决方案,请使用循环:
maxlist = []
maxlen = 0
for el in inputlist:
l = len(el)
if l > maxlen:
maxlist = [el]
maxlen = l
elif l == maxlen:
maxlist.append(el)
maxlist
根据需要构建和替换where以仅保存最长的元素:
>>> inputlist = 'And so we give a demo once more'.split()
>>> maxlist = []
>>> maxlen = 0
>>> for el in inputlist:
... l = len(el)
... if l > maxlen:
... maxlist = [el]
... maxlen = l
... elif l == maxlen:
... maxlist.append(el)
...
>>> maxlist
['give', 'demo', 'once', 'more']