Pythonic方式有条件地分配变量

时间:2022-04-12 22:49:32

Any suggestions on how to do that in Python?

有关如何在Python中执行此操作的任何建议?

if x():
  a = 20
  b = 10
else:
  a = 10
  b = 20

I can swap them as below, but it's not as clear (nor very pythonic IMO)

我可以如下交换它们,但它不是那么清楚(也不是非常pythonic的IMO)

a = 10
b = 20
if x():
  [a, b] = [b, a]

2 个解决方案

#1


11  

(a,b) = (20,10) if x() else (10,20)

#2


5  

Swapping values with a, b = b, a is considered idiomatic in Python.

使用a,b = b,a交换值在Python中被认为是惯用的。

a, b = 10, 20
if x(): a, b = b, a

One nice thing is about this is you do not repeat the 10 and 20, so it is a little DRY-er.

一个好处是关于这是你不重复10和20,所以这是一个小干。

#1


11  

(a,b) = (20,10) if x() else (10,20)

#2


5  

Swapping values with a, b = b, a is considered idiomatic in Python.

使用a,b = b,a交换值在Python中被认为是惯用的。

a, b = 10, 20
if x(): a, b = b, a

One nice thing is about this is you do not repeat the 10 and 20, so it is a little DRY-er.

一个好处是关于这是你不重复10和20,所以这是一个小干。