从多个列表中生成元素的组合 [英] Generate combinations of elements from multiple lists

查看:185
本文介绍了从多个列表中生成元素的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个函数,它将可变数量的列表作为输入(即,任意参数列表)。
我需要将每个列表中的每个元素与所有其他列表中的每个元素进行比较,但是我找不到任何方法来解决这个问题。

解决方案

itertools 模块提供了许多有用的工具只是为了这样的任务。您可以通过将以下示例集成到您的特定比较逻辑中来适应您的任务。



请注意,以下假设可交换函数。例如:

 

import itertools
$ b $ def def generate_pairs(* args):
#假设函数是可交换的
for i,l in enumerate(args,1):
for itertools.product(l,itertools.chain(* args [i:])):
yield(x,y)

您可以使用列表字符串以及
for x,y in generate_pairs(ab,cd,ef):
print(x,y)

#例如apply你的比较逻辑
打印任何(x == y for x,y in generate_pairs(ab,cd,ef))
打印全部(x!= y for x,y in generate_pairs(ab,cd,ef))

输出:


$ b $

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


I'm making a function that takes a variable number of lists as input (i.e., an arbitrary argument list). I need to compare each element from each list to each element of all other lists, but I couldn't find any way to approach this.

解决方案

The itertools module provides a lot of useful tools just for such tasks. You can adapt the following example to your task by integrating it into your specific comparison logic.

Note that the following assumes a commutative function. That is, about half of the tuples are omitted for reasons of symmetry.

Example:

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"))

Output:

$ 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

这篇关于从多个列表中生成元素的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆