完整代码:
cp1=[1,2,3,4,5,6]
cp1=[1,2,3,4,5,6]
cn1=[7,8,9,10,11,12]
cn2=[13,14,15,16,17,18]
cn3=[19,20,21,22,23,24]
cn4=[25,26,27,28,29,30]
import itertools
sets = [cp1,cn1];
ks = [3,2]
for i in itertools.product(*[itertools.combinations(set, k) for set, k in zip(sets, ks)]):
a = i[0]+i[1]
for i in itertools.permutations(a) :
i_sum1 = i[0] + i[1]
i_sum2 = i_sum1 + i[2]
i_sum3 = i_sum2 + i[3]
i_sum4 = i_sum3 + i[4]
i2_sum1 = i[1] + i[2]
i2_sum2 = i2_sum1 + i[3]
i2_sum3 = i2_sum2 + i[4]
i3_sum1 = i[2] + i[3]
i3_sum2 = i3_sum1 + i[4]
i4_sum1 = i[3] + i[4]
allsum =(i_sum1, i_sum2,i_sum3,i_sum4, i2_sum1, i2_sum2, i2_sum3, i3_sum1,i3_sum2,i4_sum1)
if (i_sum1 or i_sum2 or i_sum3 or i_sum4 or i2_sum1 or i2_sum2 or i2_sum3 or i3_sum1 or i3_sum2 or i4_sum1) not in (cn1 or cn2 or cn3) :
for b in itertools.product(cn4, repeat=2):
if (b[0] and b[1]) in allsum :
print (i,allsum)
说明:
随机列表
cp1=[1,2,3,4,5,6]
cn1=[7,8,9,10,11,12]
cn2=[13,14,15,16,17,18]
cn3=[19,20,21,22,23,24]
cn4=[25,26,27,28,29,30]
两个列表之间的组合,每个结果使用1个元素和另一个元素中的2个
import itertools
sets = [cp1,cn1];
ks = [3,2]
for i in itertools.product(*[itertools.combinations(set, k) for set, k in zip(sets, ks)]):
合并结果
a = i[0]+i[1]
结果的排列
for i in itertools.permutations(a) :
排列的具体总和
i_sum1 = i[0] + i[1]
i_sum2 = i_sum1 + i[2]
i_sum3 = i_sum2 + i[3]
i_sum4 = i_sum3 + i[4]
i2_sum1 = i[1] + i[2]
i2_sum2 = i2_sum1 + i[3]
i2_sum3 = i2_sum2 + i[4]
i3_sum1 = i[2] + i[3]
i3_sum2 = i3_sum1 + i[4]
i4_sum1 = i[3] + i[4]
allsum =(i_sum1, i_sum2,i_sum3,i_sum4, i2_sum1, i2_sum2, i2_sum3, i3_sum1,i3_sum2,i4_sum1)
仅打印特定结果:
如果任何总和在任何列表cn1,cn2或cn3中,则避免结果: (这是我遇到问题的地方)
if (i_sum1 or i_sum2 or i_sum3 or i_sum4 or i2_sum1 or i2_sum2 or i2_sum3 or i3_sum1 or i3_sum2 or i4_sum1) not in (cn1 or cn2 or cn3) :
仅打印包含特定列表的2个元素的剩余结果,cn4 (及此处)
for b in itertools.product(cn4, repeat=2):
if (b[0] and b[1]) in allsum :
print (i,allsum)
输出:
第一个结果是(1, 2, 3, 7, 12) (3, 6, 13, 25, 5, 12, 24, 10, 22, 19)
它表明6和7部分都不起作用。 6ª应该防止它,因为它包含(13,12,24,22,19),cn1,cn2和cn3的元素。 7ª应该阻止它,因为它不包含cn4的两个元素,但只包含一个“25”。
答案 0 :(得分:0)
使用集来测试会员资格。
q = set(cn1)
q.update(cn2)
q.update(cn3)
# or
##q = set(itertools.chain(cn1, cn2, cn3))
# or
##q = set(n for item in (cn1, cn2, cn3) for n in item)
#fake i_sums
z = [25, 26, 27, 28, 2]
z = set(z)
#for your code
##z = set(i_sum1, i_sum2, i_sum3, i_sum4, i2_sum1, i2_sum2, i2_sum3, i3_sum1, i3_sum2, i4_sum1)
>>> q.isdisjoint(z)
True
>>> if q.isdisjoint(z):
print('doit')
doit
>>>