组合和排列问题

2024-06-26 02:43:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,比如说[(1,1,1),(0,0,0),(0,0,0)],我想生成q lenght列表中n个元素的所有排列,丢弃等价的元素。我是说:

输入

[1,1,1,0,0,0,0,0,0] 

输出

[[(1,1,1),(0,0,0),(0,0,0)], <----- keep this
[(1,1,0),(1,0,0),(0,0,0)], <----- keep this
[(1,1,0),(0,1,0),(0,0,0)], <----- disgard this
[(1,1,0),(0,0,1),(0,0,0)], <----- disgard this
[(1,1,0),(0,0,0),(1,0,0)], <----- keep this
...
...
...
...
[(0,0,0),(1,0,0),(1,0,1)], <----- keep this
[(0,0,0),(1,0,0),(0,1,1)], <----- disgard this
[(0,0,0),(0,1,0),(1,0,1)], <----- disgard this
[(0,0,0),(0,1,0),(0,1,1)], <----- disgard this
[(0,0,0),(0,0,1),(1,0,1)], <----- disgard this
[(0,0,0),(0,0,1),(0,1,1)], <----- disgard this
[(0,0,0),(0,0,0),(1,1,1)]] <----- keep this

这是一个非常简单的任务,有一些嵌套的for cicle,和sum for function,但是我不知道如何使用ipertools实现这一点。 有什么建议吗?你知道吗

谢谢。你知道吗


Tags: 元素列表forfunctionthis建议sum等价
2条回答

你可以这样得到排列:

from itertools import permutations 
permut = permutations([1,1,1,0,0,0,0,0,0]) 

for i in list(permut): 
    print(i)

如果只想删除所有重复项,可以使用sumpy:

from sympy.utilities.iterables import multiset_permutations
list(multiset_permutations([1,1,1,0,0,0,0,0,0]))

如果需要其他的东西,尽管问。你知道吗

似乎你想从你的物品列表中列出所有可能的方法来执行3次弃牌,每一次由3张牌组成。我建议您对您的选择做一个更好的映射,例如[3, 2, 0]而不是[(0,0,0),(1,0,0),(1,0,1)],其中[3, 2, 0]意味着为每个丢弃开始列表的索引。这种情况可以说明如下:

  • [1,1,1,0,0,0,0,0,0],从index=3开始取出物品
  • [1,1,1,0,0,0],从index=2开始取出物品->
  • [1,1,0],从index=0开始取出物品->
  • []

解决方案的下一步是考虑所有可能的指数选择是什么样的。很明显:

  • 第一个索引不超过6(因为列表有9项)
  • 第二个索引不超过3(因为列表有6个项目)
  • 第三个索引是0(因为列表有0项)

一般来说,我建议生成所有可能的选项,并手动放弃每个选项:

from itertools import product
d = [1,1,1,0,0,0,0,0,0]
n = 3
starting_indices = [range(len(d)-(n-1)-n*m) for m in range(len(d)//n)]
choices = []
for idx_sequence in product(*starting_indices):
    current_d = d.copy()
    current_choice = []
    for id in idx_sequence:
        current_choice.append(current_d[id: id+n])
        del current_d[id: id+n]
    choices.append(current_choice)
print(choices)

注:

有些选择可能重复

更新:

如果将这些行添加到脚本中,则可以消除重复的选择:

choices = set([tuple(tuple(m) for m in n) for n in choices]) #if you need to remove duplicates
choices = [list(list(m) for m in n) for n in choices] #if you need to set type back

输出:

[[0, 0, 0], [1, 1, 1], [0, 0, 0]]
[[0, 0, 0], [1, 0, 0], [1, 1, 0]]
[[0, 0, 0], [1, 1, 0], [1, 0, 0]]
[[0, 0, 0], [0, 0, 0], [1, 1, 1]]
[[1, 1, 1], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [0, 0, 0], [1, 1, 0]]
[[1, 0, 0], [1, 1, 0], [0, 0, 0]]
[[1, 1, 0], [1, 0, 0], [0, 0, 0]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 1, 0], [0, 0, 0], [1, 0, 0]]

相关问题 更多 >