简体   繁体   English

两个列表的值的组合

[英]combinations of the values of two lists

I am looking for an idiomatic way to combine an n-dimensional vector (given as a list) with a list of offsets, that shall be applied to every dimensions. 我正在寻找一种惯用的方法,将n维向量(作为列表提供)与偏移量列表相结合,该偏移量应适用于每个尺寸。 Ie: Given I have the following values and offsets: 即:鉴于我有以下值和偏移量:

v = [5, 6]
o = [-1, 2, 3]

I want to obtain the following list: 我想获得以下列表:

n = [[4, 5], [7, 5], [8, 5], [4, 8], [7, 8], [8, 8], [4, 9], [7, 9], [8, 9]]

originating from: 源于:

n = [[5-1, 6-1], [5+2, 6-1], [5+3, 6-1], [5-1, 6+2], [5+2, 6+2], [5+3, 6+2], [5-1, 6+3], [5+2, 6+3], [5+3, 6+3]]

Performance is not an issue here and the order of the resulting list also does not matter. 这里的性能不是问题,结果列表的顺序也无关紧要。 Any suggestions on how this can be produced without ugly nested for loops? 关于如何在没有丑陋的for循环嵌套的情况下产生任何建议? I guess itertools provides the tools for a solution, but I did not figure it out yet. 我猜itertools提供了解决方案的工具,但我还没有弄清楚。

from itertools import product    

[map(sum, zip(*[v, y])) for y in product(o, repeat=2)]

or, as falsetru and Dobi suggested in comments: 或者,如falsetru和Dobi在评论中建议的那样:

[map(sum, zip(v, y)) for y in product(o, repeat=len(v))]

itertools.product() gives you the desired combinations of o . itertools.product()为您提供所需的o组合。 Use that with a list comprehension to create n : 将其与列表推导一起使用来创建n

from itertools import product

n = [[v[0] + x, v[1] + y] for x, y in product(o, repeat=2)]

Demo: 演示:

>>> [[v[0] + x, v[1] + y] for x, y in product(o, repeat=2)]
[[4, 5], [4, 8], [4, 9], [7, 5], [7, 8], [7, 9], [8, 5], [8, 8], [8, 9]]

Use itertools.product: 使用itertools.product:

>>> import itertools
>>> 
>>> v = [5, 6]
>>> o = [-1, 2, 3]
>>> 
>>> x, y = v
>>> [[x+dx, y+dy] for dx, dy in itertools.product(o, repeat=2)]
[[4, 5], [4, 8], [4, 9], [7, 5], [7, 8], [7, 9], [8, 5], [8, 8], [8, 9]]

originating from: 源于:

[[5-1, 6-1], [5-1, 6+2], [5-1, 6+3], [5+2, 6-1], [5+2, 6+2], [5+2, 6+3], [5+3, 6-1], [5+3, 6+2], [5+3, 6+3]]

您可以使用itertools模块获取所有排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM