对列表中的每一对元素进行操作

编程入门 行业动态 更新时间:2024-10-27 05:33:23
本文介绍了对列表中的每一对元素进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用 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,4

permutations() 生成每对唯一元素的所有唯一排序,消除 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.

更多推荐

对列表中的每一对元素进行操作

本文发布于:2023-10-28 18:47:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537467.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   操作   列表中

发布评论

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

>www.elefans.com

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