我有这个元组列表
a = [(1, 2), (2, 1)]
需要所有可能的正负组合:
b = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
我试过使用
itertools.product()
:
xs = list(product(*([[i, -j] for (i, j) in b])))
ys = list(product(*([[-i, j] for (i, j) in b])))
xs + ys
但它不会生成正确的数字:
>>>xs + ys
[(1, 2), (1, -1), (-2, 2), (-2, -1), (-1, -2), (-1, 1), (2, -2), (2, 1)]
你应该在标志上执行
product
:
[(sx * x, sy * y) for x, y in a for sx, sy in product((1, -1), repeat=2)]
您还可以在嵌套的
a
中包含product
:
[(sx * x, sy * y) for (x, y), (sx, sy) in product(a, product((1, -1), repeat=2))]
或将数字和符号序列映射到乘法运算符:
from operator import mul
[tuple(map(mul, *t)) for t in product(a, product((1, -1), repeat=2))]
所有三个表达式都会返回:
[(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
(注意:目前这个问题是模棱两可的。一旦他们澄清,我可能需要更新这些。)
对于任意长度的元组:
[p for t in a for p in product(*((x, -x) for x in t))]
或与
operator.neg
:
[p for t in a for p in product(*zip(t, map(neg, t)))]
或者在没有任何 Python 循环的情况下,使用
chain
中的 repeat
/starmap
/itertools
(这是从上述解决方案直接转换而来):
[*chain(*starmap(product, map(zip, a, map(map, repeat(neg), a))))]
对于长度为 2 的元组:
[(X, Y) for x, y in a for X in (x, -x) for Y in (y, -y)]
代码:
a = [(1, 2), (2, 1)]
res1=[]
for x in a:
for i in [x[0], -x[0]]:
for j in [x[1], -x[1]]:
res1.append((i,j))
#Through list comprehension
res2=[(i,j) for x in a for i in [x[0],-x[0]] for j in [x[1],-x[1]]]
#Output
print(res1)
print(res2)
输出:
[(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
[(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
使用
itertools
代码:
import itertools
a=[(1, 2), (2, 1)]
xs=list(itertools.product(*map(lambda x: (x, -x), a[0])))
ys=list(itertools.product(*map(lambda x: (x, -x), a[1])))
print(xs+ys) #Same output as above
这是您要解决的问题的解决方案...
xs = list(itertools.product(*([[(i),(-i)] for (i,j) in var_b])))
ys = list(itertools.product(*([[(j),(-j)] for (i,j) in var_b])))
print (xs + ys)
Output
[(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
a = [(1, 2), (2, 1)]
b = []
for x, y in a:
for i in [-1, 1]:
for j in [-1, 1]:
b.append((x*i, y*j))
print(b)