一个范围内列表的所有可能组合



我有这个列表:

输入:[1,7,8,9,10,11,19]

我正在寻找这个输出:

输出:[[1],[7],[7,8],[7,8,9],[7,8,9,10],[7,8,9,10,11],[8,9,10,11],[9,10,11],[10,11],[11] [19]]

在输出中,我有5位数范围内的所有组。1(1,2,3,4,5)中,(2,3,4,5,6)中没有,然后(3,4,5,6,7)中有7,依此类推…

我试过这个程序,但它没有给我我正在寻找的结果

playersHand = []
table = [1,7,8,9,10,11,19]
for n in range(len(table)):
playersHand.append(int(table[n]))

playersHand.sort()
cardsSet = set(playersHand)
possibleStraight = []
possibleStraightgrade = []
possibleStraightgradelist = []

for f in cardsSet:
possibleStraightset = cardsSet.intersection(range(f,f+5))
possibleStraightlist = list(possibleStraightset)
possibleStraightlist.sort()
possibleStraight.append(possibleStraightlist)

for n in possibleStraight:
if n != 0:
possibleStraightgrade = max(n)
possibleStraightgradelist.append(possibleStraightgrade)
print(possibleStraight)

,它给了我这个:

[[1], [7, 8, 9, 10, 11], [8, 9, 10, 11], [9, 10, 11], [10, 11], [11], [19]]

您可以使用列表推导式更直接地获得结果,并设置与潜在序列5的交集:

L = [1,7,8,9,10,11,19]
S = [ sorted(s)
for f in range(min(L),max(L)-3)                    # potential series
for s in [set(range(f,f+5)).intersection(L)] if s] # intersection
print(S)
[[1], [7], [7, 8], [7, 8, 9], [7, 8, 9, 10], [7, 8, 9, 10, 11], 
[8, 9, 10, 11], [9, 10, 11], [10, 11], [11], [19]]

你可以试试:

a = [1,7,8,9,10,11,19]
# get all tuples
out = [t for i in range(max(a)) if (t:=tuple(x for x in a if x in range(i, i+5)))]
# remove possible duplicates while preserving order
out = list(dict.fromkeys(out))  

它给:

[(1,),
(7,),
(7, 8),
(7, 8, 9),
(7, 8, 9, 10),
(7, 8, 9, 10, 11),
(8, 9, 10, 11),
(9, 10, 11),
(10, 11),
(11,),
(19,)]

最新更新