-->

产生从多个列表元素的组合(Generate combinations of elements fro

2019-11-02 02:47发布

我正在做一个函数,变量数列表作为输入(即的任意参数列表 )。 我需要每一个元素从每个列表中的所有其他列表中的每个元素进行比较,但我找不到任何方式接近这一点。

Answer 1:

该itertools模块提供了很多有用的工具,只是这样的任务。 您可以通过其集成到您的具体比较逻辑下面的例子适应你的任务。

请注意,以下假定交换功能。 也就是说,对元组的一半,省略了对称的原因。

例:

import itertools

def generate_pairs(*args):
    # assuming function is commutative
    for i, l in enumerate(args, 1):
        for x, y in itertools.product(l, itertools.chain(*args[i:])):
            yield (x, y)

# you can use lists instead of strings as well
for x, y in generate_pairs("ab", "cd", "ef"):
    print (x, y)

# e.g., apply your comparison logic
print any(x == y for x, y in generate_pairs("ab", "cd", "ef"))
print all(x != y for x, y in generate_pairs("ab", "cd", "ef"))

输出:

$ python test.py
('a', 'c')
('a', 'd')
('a', 'e')
('a', 'f')
('b', 'c')
('b', 'd')
('b', 'e')
('b', 'f')
('c', 'e')
('c', 'f')
('d', 'e')
('d', 'f')
False
True


Answer 2:

根据你的目标,你可以使用一些itertools工具。 例如,你可以使用itertools.product*args

from itertools import product
for comb in product(*args):
    if len(set(comb)) < len(comb):
        # there are equal values....

但目前它不是从你的问题,你想达到什么是很清楚。 如果我没有理解错的话,你可以尝试陈述的问题更具体的方式。



Answer 3:

我觉得@ LevLeitsky的答案是从列表中的变量数做主持的项目循环的最佳方式。 但是,如果目的环路只是为了找到从列表中对项目之间的共同元素,我会做有点不同。

下面是找到每对表之间的公共元素的方法:

import itertools

def func(*args):
    sets = [set(l) for l in args]
    for a, b in itertools.combinations(sets, 2):
        common = a & b # set intersection
        # do stuff with the set of common elements...

我不知道你需要的公共元素做什么,所以我会离开它。



Answer 4:

如果你想要的参数作为字典

def kw(**kwargs):
    for key, value in kwargs.items():
        print key, value

如果你希望所有的参数为列表:

 def arg(*args):
        for item in args:
            print item

您可以同时使用

def using_both(*args, **kwargs) :
     kw(kwargs)
     arg(args)

这样称呼它是:

using_both([1,2,3,4,5],a=32,b=55)


文章来源: Generate combinations of elements from multiple lists