使用 Python,我想比较列表中的每个可能的对.
Using Python, I'd like to compare every possible pair in a list.
假设我有
my_list = [1,2,3,4]我想对列表中 2 个元素的每个组合执行一个操作(我们称之为 foo).
I'd like to do an operation (let's call it foo) on every combination of 2 elements from the list.
最终结果应该是一样的
foo(1,1) foo(1,2) ... foo(4,3) foo(4,4)我的第一个想法是手动遍历列表两次,但这似乎不是很pythonic.
My first thought was to iterate twice through the list manually, but that doesn't seem very pythonic.
推荐答案查看 itertools 模块中的 product().它完全符合您的描述.
Check out product() in the itertools module. It does exactly what you describe.
import itertools my_list = [1,2,3,4] for pair in itertools.product(my_list, repeat=2): foo(*pair)这相当于:
my_list = [1,2,3,4] for x in my_list: for y in my_list: foo(x, y)还有两个非常相似的函数,permutations() 和 combinations().为了说明它们的不同之处:
There are two very similar functions as well, permutations() and combinations(). To illustrate how they differ:
product() 生成所有可能的元素对,包括所有重复项:
product() generates every possible pairing of elements, including all duplicates:
1,1 1,2 1,3 1,4 2,1 2,2 2,3 2,4 3,1 3,2 3,3 3,4 4,1 4,2 4,3 4,4permutations() 生成每对唯一元素的所有唯一排序,消除 x,x 重复项:
permutations() generates all unique orderings of each unique pair of elements, eliminating the x,x duplicates:
. 1,2 1,3 1,4 2,1 . 2,3 2,4 3,1 3,2 . 3,4 4,1 4,2 4,3 .最后,combinations() 只生成每对唯一的元素,按字典顺序:
Finally, combinations() only generates each unique pair of elements, in lexicographic order:
. 1,2 1,3 1,4 . . 2,3 2,4 . . . 3,4 . . . .这三个函数都是在 Python 2.6 中引入的.
All three of these functions were introduced in Python 2.6.
更多推荐
对列表中的每一对元素进行操作
发布评论