是否有可能在元组中有一个if?

时间:2013-06-12 08:44:41

标签: python if-statement conditional-expressions

我想建立类似的东西:

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 个答案:

答案 0 :(得分: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')

这是一个conditional expression,也称为三元条件运算符。

答案 1 :(得分:3)

可以建议你跟随

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')

答案 2 :(得分:1)

是的,你可以,但为此,你的三元条件必须是有效条件,即你也需要一个else条款。

python中的三元运算符:

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

您的代码:

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

答案 3 :(得分:0)

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

A= ('a', 'b', 'c' if condition else 'd')