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