سؤال

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. I.e.: 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? I guess itertools provides the tools for a solution, but I did not figure it out yet.

هل كانت مفيدة؟

المحلول

from itertools import product    

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

or, as falsetru and Dobi suggested in comments:

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

نصائح أخرى

itertools.product() gives you the desired combinations of o. Use that with a list comprehension to create 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:

>>> 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]]

You may use itertools module to get all permutations.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top