[英]Pythonic way to do conditionally assign variables
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]
(a,b) = (20,10) if x() else (10,20)
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
,所以它是一个小干 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.