[英]Unpack tuples in list comprehension with a condition
I'd like to build one of these lists of tuples:我想构建这些元组列表之一:
(a, 0), (-a, 0) (b, 0), (-b, 0)
(0, a), (0, -a) (0, b), (0, -b)
from scalars a
and b
.从标量
a
和b
。
based on a condition:基于一个条件:
c = a > b
This is my attempt:这是我的尝试:
a = 5
b = 2
c = a > b
# Try build two tuples per element, e.g. (5, 0), (-5, 0) (2, 0), (-2, 0)
# This syntax is illegal
#f2 = [(m,0), (-m,0) if c else (0,m), (-0,-m) for m in (a,b)]
# This syntax works but creates tuples of tuples
f2 = [tuple(((m,0), (-m,0))) if c else tuple(((0,m), (-0,-m))) for m in (a,b)]
print(*f2) # ((5, 0), (-5, 0)) ((2, 0), (-2, 0))
# This syntax is illegal
#f3 = [*tuple(((m,0), (-m,0))) if c else *tuple(((0,m), (-0,-m))) for m in (a,b)]
#print(*f3)
f2
builds a list of two tuples of two tuples: ((5, 0), (-5, 0)) ((2, 0), (-2, 0))
. f2
构建两个元组的两个元组的列表: ((5, 0), (-5, 0)) ((2, 0), (-2, 0))
。
Using *
operator in f3
to unpack the outer tuples triggers a syntax error.在
f3
中使用*
运算符解包外部元组会触发语法错误。
What is the correct syntax?什么是正确的语法?
Also I don't understand why f2 is ((5, 0), (-5, 0)) ((2, 0), (-2, 0))
, where the outer tuples are not separated by a ,
?另外我不明白为什么 f2 是
((5, 0), (-5, 0)) ((2, 0), (-2, 0))
,其中外部元组不被 a ,
?
You can do it with lambda functions.您可以使用 lambda 函数来完成。
x1 = lambda x : (x,0)
y1 = lambda x : (-x,0)
x2 = lambda x : (0,x)
y2 = lambda x : (-0,-x)
f2 = [f1(m) if c else f2(m) for m in (a,b) for f1,f2 in zip((x1,y1),(x2,y2))]
Output: Output:
[(5, 0), (-5, 0), (2, 0), (-2, 0)]
A little bit over-engineered but makes sense.有点过度设计,但有道理。
EDIT编辑
Also you can use chain from itertools to put 2 items in a single list comprehension.您也可以使用 itertools 中的链将 2 个项目放在一个列表理解中。
from itertools import chain
f2 = list(
chain.from_iterable(
((m,0), (-m,0)) if c else ((0,m), (-0,-m)) for m in (a,b)
))
In this case you don't really need any loops, you can use condition:在这种情况下,您实际上不需要任何循环,您可以使用条件:
a = 5
b = 2
c = a > b
f2 = [(a, 0), (-a, 0), (b, 0), (-b, 0)] if c else [(0, a), (0, -a), (0, b), (0, -b)]
If (for some reason) you want to solve it with list comprehension, you can use next:如果(出于某种原因)你想用列表理解来解决它,你可以使用下一个:
f2 = [(j, 0) if c else (0, j) for i in (a, b) for j in (i, -i)]
You can help my country, check my profile info .你可以帮助我的国家,查看我的个人资料信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.