我有一个清单:
a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]
是否可以创建一个显示不同连续元素的最长列表的函数?
请展示如何操作
在这种情况下,答案应该是:
13, 14, 15, 16, 17, 18
答案 0 :(得分:7)
假设您的列表已排序:
>>> from itertools import groupby
>>> z = zip(a, a[1:])
>>> tmp = [list(j) for i, j in groupby(z, key=lambda x: (x[1] - x[0]) <= 1)]
>>> max(tmp, key=len)
[(13, 14), (14, 15), (15, 16), (16, 16), (16, 17), (17, 18)]
>>> list(range(_[0][0], _[-1][-1]+1))
[13, 14, 15, 16, 17, 18]
ETA:修复最后一步;
答案 1 :(得分:2)
最简单的做法似乎是遍历列表一次,构建您可以找到的任何序列,然后打印最长的序列。
a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]
seqlist = [] # List of Sequences
seq = [] # Current Sequence
last = -1
for item in a:
# Start a new sequence if the gap from the last item is too big
if item - last > 1:
seqlist.append(seq)
seq = []
# only add item to the sequence if it's not the same as the last
if item != last:
seq.append(item)
last = item
# Print longest sequence found
print max(seqlist)
答案 2 :(得分:0)
可能有更多的pythonic方式,但我现在想不到它,所以这里有一个非常基本的解决方案:
def longestDistinctConsecutiveList ( lst ):
lst = list( set( lst ) ) # get rid of duplicated elements
lst.sort() # sort
s, l = 0, 0
for i in range( len( lst ) ):
for j in range( i, len( lst ) ):
if lst[j] - lst[i] == len( lst[i:j] ) > l:
l = 1 + a[j] - a[i]
s = i
return lst[s:s+l]