python 中任意数量参数的笛卡尔积 3.6

Cartesian product of arbitrary number of arguments in python 3.6

我正在尝试编写一个 python 3.6 命令行程序,它接受一个或多个列表作为参数,然后 returns 这些列表的笛卡尔积,可能采用去重形式。

我可以使用一个和两个列表参数正常工作,但我不知道如何让程序正确处理三个或更多参数。

所需的输出是笛卡尔积,其中包括作为参数传递到命令行的每个列表。

这是我目前的代码:

def createArgumentParser():

    from argparse import ArgumentParser

    __parser = ArgumentParser()
    __parser.add_argument("list", type=list, nargs="+", help="List(s) to compute the cartesian product of")
    __parser.add_argument("-u", "--unique", action="store_true", help="Deduplicate lists so that they become sets of unique elements")
    __parser.add_argument("-U", "--Universally_unique", action="store_true", help="Deduplicate the resulting cartesian product so that the final result is a set of unique elements")
    return __parser.parse_args()


def cartesianProduct(__unique, __Universally_unique, *__list):

    from itertools import product

    __cartesianProduct = product([])

    if __unique:
        __cartesianProduct = product(sorted(set(__list[0])), sorted(set(__list[len(__list)-1])))
    else:
        __cartesianProduct = product(__list[0], __list[len(__list)-1])
    if __Universally_unique:
        __cartesianProduct = sorted(set(__cartesianProduct))
        for __element in __cartesianProduct:
            if __element[0] == __element[1]:
            __cartesianProduct.remove(__element)
    return __cartesianProduct


def main():

    __args = createArgumentParser()

    for __element in cartesianProduct(__args.unique, __args.Universally_unique, *__args.list):
        print(__element)

运行 带有命令行参数的程序 abc 123 def returns this:

('a', 'd')
('a', 'e')
('a', 'f')
('b', 'd')
('b', 'e')
('b', 'f')
('c', 'd')
('c', 'e')
('c', 'f')

笛卡尔积中缺少 123 部分。我该如何解决?

要获取列表中所有项目的笛卡尔积,您可以使用 * 运算符执行参数解包。这有时被称为 "splat" 解包。

from itertools import product

src = ['abc', '123',  'def']
cartesian_product = [''.join(t) for t in product(*src)]
print(cartesian_product)

输出

['a1d', 'a1e', 'a1f', 'a2d', 'a2e', 'a2f', 'a3d', 'a3e', 'a3f', 'b1d', 'b1e', 'b1f', 'b2d', 'b2e', 'b2f', 'b3d', 'b3e', 'b3f', 'c1d', 'c1e', 'c1f', 'c2d', 'c2e', 'c2f', 'c3d', 'c3e', 'c3f']