[英]How to generate sequential sublist of a list with a skip
I wanted to generate sublist of a list with skips.我想用跳过生成列表的子列表。 To clarify given a list for example
[1,3,6,2,4]
澄清给出的列表,例如
[1,3,6,2,4]
I want to get all sublists like: [1,3], [1,3,6], [1,3,4], [1,3,6,2], [1,3,2,4], [1,3,6,4], [1,6], [1,6,2], [1,6,4]...
and so on.我想获得所有子列表,如:
[1,3], [1,3,6], [1,3,4], [1,3,6,2], [1,3,2,4], [1,3,6,4], [1,6], [1,6,2], [1,6,4]...
等等。 So far I only now how to generate consequative sublists like [1,3], [1,3,6],[1,3,6,2], [1,3,6,2,4]
but I am having hard time getting sublist with skip like [1,3,2,4] or [1,3,6,4].到目前为止,我只知道如何生成诸如
[1,3], [1,3,6],[1,3,6,2], [1,3,6,2,4]
类的连续子列表[1,3], [1,3,6],[1,3,6,2], [1,3,6,2,4]
但我有很难通过像 [1,3,2,4] 或 [1,3,6,4] 这样的跳过来获得子列表。 Please help me out.请帮帮我。
def sub_lists(list1):
sublist = [[]]
for i in range(len(list1) + 1):
for j in range(i + 1, len(list1) + 1):
sub = list1[i:j]
sublist.append(sub)
return sublist
l1 = [1, 2, 3, 4]
print(sub_lists(l1))
Use itertools.combinations
使用
itertools.combinations
from itertools import combinations
x = [1,3,6,2,4]
y = []
for i in range(1, len(x)):
y.extend(combinations(x, i+1))
print(y)
Output:输出:
[(1, 3), (1, 6), (1, 2), (1, 4), (3, 6), (3, 2), (3, 4), (6, 2), (6, 4),
(2, 4), (1, 3, 6), (1, 3, 2), (1, 3, 4), (1, 6, 2), (1, 6, 4), (1, 2, 4),
(3, 6, 2), (3, 6, 4), (3, 2, 4), (6, 2, 4), (1, 3, 6, 2), (1, 3, 6, 4),
(1, 3, 2, 4), (1, 6, 2, 4), (3, 6, 2, 4), (1, 3, 6, 2, 4)]
Edit编辑
To get first element to be the first use sorted
使第一个元素成为第一个使用
sorted
y = sorted(y, key=lambda x:x[0])
I hope this helps我希望这有帮助
def skipList(lst):
for i in lst:
x = [i]
for j in lst:
if j == i:
continue
x.append(j)
print(x)
a = [1,3,6,2,4]
skipList(a)
You can use recursion with a generator:您可以将递归与生成器一起使用:
d = [1,3,6,2,4]
def combos(v, c = []):
yield c
yield from ([] if not v else combos(v[1:], c+[v[0]]))
yield from ([] if not v else combos(v[1:], c))
print(list(filter(None, combos(d))))
Output:输出:
[[1], [1, 3], [1, 3, 6], [1, 3, 6, 2], [1, 3, 6, 2, 4], [1, 3, 6, 2], [1, 3, 6], [1, 3, 6, 4], [1, 3, 6], [1, 3], [1, 3, 2], [1, 3, 2, 4], [1, 3, 2], [1, 3], [1, 3, 4], [1, 3], [1], [1, 6], [1, 6, 2], [1, 6, 2, 4], [1, 6, 2], [1, 6], [1, 6, 4], [1, 6], [1], [1, 2], [1, 2, 4], [1, 2], [1], [1, 4], [1], [3], [3, 6], [3, 6, 2], [3, 6, 2, 4], [3, 6, 2], [3, 6], [3, 6, 4], [3, 6], [3], [3, 2], [3, 2, 4], [3, 2], [3], [3, 4], [3], [6], [6, 2], [6, 2, 4], [6, 2], [6], [6, 4], [6], [2], [2, 4], [2], [4]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.