gpt4 book ai didi

python - 是否可以在元组中使用 if ?

转载 作者:行者123 更新时间:2023-11-28 19:44:30 24 4
gpt4 key购买 nike

我想构建类似这样的东西:

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 元组

最佳答案

是的,但是你需要一个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 ,也称为三元条件运算符。

关于python - 是否可以在元组中使用 if ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17061231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com