繁体   English   中英

Python 多个不同大小列表的组合

[英]Python combinations of multiple list of different sizes

我正在尝试在多个列表之间交换项目,我想知道是否有任何方法可以在多个不同大小的列表之间生成组合?

例如,我有这 3 个列表:

a = [(0, 0), (1, 0), (2, 0)]
b = [(0, 2), (1, 2), (2, 2)]
c = [(0, 3), (1, 3)]

预期结果:

a : [(0, 3), (0, 2), (0, 0)]
b : [(1, 3), (1, 2), (1, 0)]
c : [(2, 2), (2, 0)]

a : [(0, 3), (0, 2), (0, 0)]
b : [(1, 3), (1, 2), (2, 0)]
c : [(2, 2), (1, 0)]

...

a : [(0, 3), (0, 2)]
b : [(1, 3), (1, 2), (0, 0)]
c : [(2, 2), (2, 0), (1, 0)]

我在这里找到了这段代码( 多个列表的 python 组合):

import itertools as it
import numpy as np

a = [(0, 0), (1, 0), (2, 0)]
b = [(0, 2), (1, 2), (2, 2)]
c = [(0, 3), (1, 3)]

def combination(first, *rest):
    for i in it.product([first], *(it.permutations(j) for j in rest)):
        yield tuple(zip(*i))

for i in combination(c, b, a):
    print("a :", list(i[0]))
    print("b :", list(i[1]))
    print("c :", list(i[2]))

如果列表大小相同,它就可以很好地工作。

尝试

  1. None添加到您的列表中,以便它们都具有相同的长度,
  2. 使用sympy.utilities.iterables.multiset_permutations而不是it.permutations
  3. 最后从 output 中过滤掉None值。

这应该以自然的方式概括您对相同大小列表的方法:

import itertools as it
from sympy.utilities.iterables import multiset_permutations

a = [(0, 0), (1, 0), (2, 0)]
b = [(0, 2), (1, 2), (2, 2)]
c = [(0, 3), (1, 3), None]

def combination(first, *rest):
    for i in it.product([first], *(multiset_permutations(j) for j in rest)):
        yield tuple(zip(*i))

for i in combination(c, b, a):
    print("a :", [val for val in i[0] if val])
    print("b :", [val for val in i[1] if val])
    print("c :", [val for val in i[2] if val])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM