3

我想构建类似的东西:

A = (
  'parlament',
  'queen/king' if not country in ('england', 'sweden', …),
  'press',
  'judges'
)

有没有办法建立这样的元组?

我试过了

'queen/king' if not country in ('england', 'sweden', …) else None,
'queen/king' if not country in ('england', 'sweden', …) else tuple(),
'queen/king' if not country in ('england', 'sweden', …) else (),

但没有任何效果,似乎没有元组-无元素,所以我有一个除英格兰、瑞典等国家以外的所有国家的 3 元组,我得到一个 4 元组

4

5 回答 5

8

是的,但你需要一个else声明:

>>> country = 'australia'
>>> A = (
...   'parlament',
...   'queen/king' if not country in ('england', 'sweden') else 'default',
...   'press',
...   'judges'
...      )
>>> print A
('parlament', 'queen/king', 'press', 'judges')

另一个例子:

>>> country = 'england'
>>> A = (
...   'parlament',
...   'queen/king' if not country in ('england', 'sweden') else 'default',
...   'press',
...   'judges'
...    )
>>> print A
('parlament', 'default', 'press', 'judges')

这是一个条件表达式,也称为三元条件运算符。

于 2013-06-12T08:48:07.820 回答
5

可以建议你关注

A = (('parlament',) +
     (('queen/king',) if not country in ('england', 'sweden', …) else tuple()) +
     ('press', 'judges'))

这允许您在结果元组中包含或不包含元素(与默认值不同,如果您不使用元组连接,默认值将被包含在内。

A = ('parlament',
     'queen/king' if not country in ('england', 'sweden', …) else 'default',
     'press', 'judges')
于 2013-06-12T08:49:25.830 回答
2

我遇到了类似的问题。您可以使用扩展运算符*

A = (
  'parlament',
  *(('queen/king',) if not country in ('england', 'sweden', …) else tuple()),
  'press',
  'judges'
)

看起来有点复杂,但完全符合要求。首先,它将所需的任何答案“打包”到一个元组中(产生一个空元组或一个单元素元组)。然后,它“解包”生成的元组并将其合并到主外部元组中的正确位置

于 2021-12-04T03:14:22.377 回答
1

是的,您可以,但是您的三元条件必须是有效的,即您也需要一个else子句。

python中的三元运算符:

>>> 'x' if False else 'y'
'y'

你的代码:

A = (
  'parlament',
  'queen/king' if not country in ('england', 'sweden') else 'foo',
  'press',
  'judges'
   )
于 2013-06-12T08:48:32.523 回答
0

您可以使用三元条件运算符,例如:

A= ('a', 'b', 'c' if condition else 'd')
于 2013-06-12T08:55:58.207 回答