import itertools
a=(list(itertools.combinations([3,4,5,9,17,28,30,31
], 6)))
print(len(a))
print(a)
结果为
28
[(3, 4, 5, 9, 17, 28), (3, 4, 5, 9, 17, 30), (3, 4, 5, 9, 17, 31), (3, 4, 5, 9, 28, 30), (3, 4, 5, 9, 28, 31), (3, 4, 5, 9, 30, 31), (3, 4, 5, 17, 28, 30), (3, 4, 5, 17, 28, 31), (3, 4, 5, 17, 30, 31), (3, 4, 5, 28, 30, 31), (3, 4, 9, 17, 28, 30), (3, 4, 9, 17, 28, 31), (3, 4, 9, 17, 30, 31), (3, 4, 9, 28, 30, 31), (3, 4, 17, 28, 30, 31), (3, 5, 9, 17, 28, 30), (3, 5, 9, 17, 28, 31), (3, 5, 9, 17, 30, 31), (3, 5, 9, 28, 30, 31), (3, 5, 17, 28, 30, 31), (3, 9, 17, 28, 30, 31), (4, 5, 9, 17, 28, 30), (4, 5, 9, 17, 28, 31), (4, 5, 9, 17, 30, 31), (4, 5, 9, 28, 30, 31), (4, 5, 17, 28, 30, 31), (4, 9, 17, 28, 30, 31), (5, 9, 17, 28, 30, 31)]
上面的编程有28组,其中有10组同时包含3,4,5这三个数据,怎么样新建一个列表后取消这10组数据剩下18组数据。不用这两个办法if not list(item[:3]) == [3,4,5]: 或者for item in a: if 3 not in item:result_1.append(item) else:if 4 not in item: 有没有其他的 ,
如果列表中有大量的3个相邻的数字 ,例如 a=(list(itertools.combinations([3,4,5,9,10,11,17,28,29,30,31
], 6))) 又不想3个相邻的数字组合在一起,可以用 字母 jkl 代替3个数字 j>k>l j-k==1 ,k-l==1 类似的解决吗??
观察到你的列表里没有重复数字,所以可以用集合来判断
import itertools
a=(list(itertools.combinations([3,4,5,9,17,28,30,31], 6)))
print(len(a))
print(a)
res = list()
to_remove = {3, 4, 5}
for i in a:
if to_remove.issubset(set(i)): continue
res.append(i)
print(len(res))
print(res)
a=(list(itertools.combinations([3,4,5,9,10,11,17,28,29,30,31], 6)))
res = list()
for i in a:
for j in range(3, 31):
to_remove = {j, j+1, j+2}
if to_remove.issubset(set(i)): break
else: res.append(i)
print(len(res))
print(res)
写一个方法,判断一个元素是否包含3个连续的数字,也可以为这个方法添加一个参数,判断连续n个数。然后对a中的元素e逐个判断移除:
def is_consecutive(e):
n = 3
for i in range(len(e) - n + 1):
for j in range(n):
if e[i] + j != e[i + j]:
break
else:
return True
return False
a = [e for e in a if not is_consecutive(e)]
print(len(a))
print(a)
输出:
18
[(3, 4, 9, 17, 28, 30), (3, 4, 9, 17, 28, 31), (3, 4, 9, 17, 30, 31), (3, 4, 9, 28, 30, 31), (3, 4, 17, 28, 30, 31), (3, 5, 9, 17, 28, 30), (3, 5, 9, 17, 28, 31), (3, 5, 9, 17, 30, 31), (3, 5, 9, 28, 30, 31), (3, 5, 17, 28, 30, 31), (3, 9, 17, 28, 30, 31), (4, 5, 9, 17, 28, 30), (4, 5, 9, 17, 28, 31), (4, 5, 9, 17, 30, 31), (4, 5, 9, 28, 30, 31), (4, 5, 17, 28, 30, 31), (4, 9, 17, 28, 30, 31), (5, 9, 17, 28, 30, 31)]
import itertools
arr = [3,4,5,9,17,29,30,31]
a=list(itertools.combinations(arr, 6))
n3 = [set(range(v,v+3)) for v in arr if v + 1 in arr and v + 2 in arr]
b = [v for v in a if len(v) != min([len(set(v) - s) for s in n3]) + 3]
print(len(a))
print(len(b))
print(a)
print()
print(b)
抱歉,没有问题给出。如果您有任何问题需要解决,请您提出具体的问题,我会尽力为您提供帮助。