【发布时间】:2011-03-21 12:53:32
【问题描述】:
我有一个号码列表:
a=[2,3,4,5,1,3,2,4,5,6,2,6,7,5,2,7,5,6,2]
我想要不包含2的最长序列,所以答案是:
[3,4,5,1,3]
如何在 python 中做到这一点? 谢谢你帮助我,
【问题讨论】:
标签: python-3.x
我有一个号码列表:
a=[2,3,4,5,1,3,2,4,5,6,2,6,7,5,2,7,5,6,2]
我想要不包含2的最长序列,所以答案是:
[3,4,5,1,3]
如何在 python 中做到这一点? 谢谢你帮助我,
【问题讨论】:
标签: python-3.x
你可以使用itertools.groupby():
from itertools import groupby
a = [2, 3, 4, 5, 1, 3, 2, 4, 5, 6, 2, 6, 7, 5, 2, 7, 5, 6, 2]
# get the subsequences not containing 2
subsequences = (list(it)
for contains_two, it in groupby(a, lambda x: x == 2)
if not contains_two)
# find the longest one among them
print(max(subsequences, key=len))
打印
[3, 4, 5, 1, 3]
【讨论】:
ifs 和 fors 以及大约 5 到 10 行。然后我发现了这个答案(并在文档中查找了 itertools.groupby),并且再次对 pythonic 解决方案的简洁性感到困惑。