从多个列表中生成元素的组合

编程入门 行业动态 更新时间:2024-10-28 00:25:28
本文介绍了从多个列表中生成元素的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

解决方案

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

更多推荐

从多个列表中生成元素的组合

本文发布于:2023-11-30 06:27:40,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   多个   元素   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!