【发布时间】:2022-12-24 22:48:26
【问题描述】:
我想构建这些元组列表之一:
(a, 0), (-a, 0) (b, 0), (-b, 0)-
(0, a), (0, -a) (0, b), (0, -b)
来自标量 a 和 b。
基于条件:
-
c = a > b
这是我的尝试:
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 构建两个元组的两个元组的列表:((5, 0), (-5, 0)) ((2, 0), (-2, 0))。
在f3 中使用* 运算符解压外部元组会触发语法错误。
正确的语法是什么?
另外我不明白为什么 f2 是 ((5, 0), (-5, 0)) ((2, 0), (-2, 0)),其中外部元组没有被 , 分隔?
【问题讨论】:
-
我根本不会使用循环。
[(a, 0), (-a, 0), (b, 0), (-b, 0)] if c else [(0, a), (0, -a), (0, b), (0, -b)] -
为什么你需要调用
tuple(),而你只能使用元组文字语法? -
不过,
f2 = [((m,0), (-m,0)) if c else ((0,m), (-0,-m)) for m in (a,b)]不是。您不需要在这里联系tuple(),但@OlvinRoght 的建议可能是正确的,我只是在旁边挖掘
标签: python tuples list-comprehension