如何获取值对,其中第一个值取自一个列表,第二个值取自另一个列表?
我想要类似下面的代码,但是采用“Pythonic”风格或使用标准库:
def combinations(a,b):
for i in a:
for j in b:
yield(i,j)
I want something like the code below, but in a "Pythonic" style or using the standard library:
def combinations(a,b):
for i in a:
for j in b:
yield(i,j)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这些并不是组合学意义上的真正“组合”。这些实际上是
a
和b
的笛卡尔积的元素。标准库中生成这些对的函数是itertools.product( )
:These are not really "combinations" in the sense of combinatorics. These are rather elements from the Cartesian product of
a
andb
. The function in the standard library to generate these pairs isitertools.product()
:作为 Sven 说,您的代码正在尝试获取列表
a
和b
的所有有序元素对。在这种情况下,itertools.product(a,b)
就是您想要的。相反,如果您实际上想要“组合”,即列表
a
中不同元素的无序对,那么您需要itertools.combinations(a,2)
。As Sven said, your code is attempting to get all ordered pairs of elements of the lists
a
andb
. In this caseitertools.product(a,b)
is what you want.If instead you actually want "combinations", which are all unordered pairs of distinct elements of the list
a
, then you wantitertools.combinations(a,2)
.嵌套的生成器表达式也可以工作:
A nested generator expression will work too:
itertools 库具有组合函数。就像Sven 指出,在这种情况下,
itertools.product
将是合适的函数:The itertools library has combinatorics functions. Like Sven stated,
itertools.product
would be the appropriate function in this case:我们可能会问的一个问题是您想要生成所有有序对还是所有无序对。 mhyfritz 的回答将为您提供所有有序对。
如果您希望所有无序对(即,(1, 2) 和(2, 1) 算作同一对),那么您需要过滤掉重复项。执行此操作的一个简单方法是将条件添加到生成器表达式的末尾,如下所示:
A question we might ask is whether you want to generate all ordered pairs or all unordered pairs. The nested generator expression provided in the answer by mhyfritz will give you all ordered pairs.
If you want all unordered pairs (that is, (1, 2) and (2, 1) counts as the same pair), then you need to filter out the duplicates. An easy way to do this is to add a conditional to the end of the generator expression like so:
创建一组对(偶数、奇数)组合
Create set of pairs (even,odd) combination