Python 默认值并根据其他变量设置值。如果还有或没有。

问题描述 投票:0回答:4

有时我有一个变量,我想默认为某个变量,如果设置了其他变量,请将其更改为其他变量。

问题是。什么是首选?设置默认值,然后在满足条件时更改它,或者仅设置一次条件,具体取决于添加的其他初始检查?

代码示例。

if x:
    y = '%s-other' % x
else:
    y = 'some_default'

另一个选择是。

y = 'some_default'
if x:
    y = '%s-other' % x

这并不总是传递给函数的参数,因此我不想在这里依赖 kwargs。

就个人而言,第二个对我来说似乎更清楚,但我还没有找到任何人对此有任何意见。

python coding-style syntax default-value
4个回答
5
投票

这个怎么样:

y = '%s-other' % x if x else 'some_default'

4
投票

正如 Rob 指出的那样,

y = '%s-other' % x if x else 'some_default'

是各种语言中非常常见的结构

Python 提供了更多选择,选择取决于用户

y = ['some_default','%s-other'][x!=None]

如果你正在处理字典,它已经有两个选项

  1. x.setdefault(some_key,some_default)=other
  2. 一样使用setdefault
  3. 使用 collections.defaultdict

你发布的其他人也有效但不是很pythonic但是你会遇到很多代码引用你的风格。

对我来说,只要一个程序是可读的、高效的,我们不应该太拘泥于做一些经常偏离重点的构造pythonic。


0
投票

其他答案的更多糖分:

y = x and '%s-other' % x or 'some_default'

但是这个可能会吓到人,所以我建议使用 Rob 的:)


0
投票

其他答案都没有处理更一般的

if-elif-else
案例。

当只有一个条件时,条件表达式可能是最好的方法,正如其他答案指出的那样:

option = 42 if condition else 'default'

但是如果有两个或更多的条件就变得很麻烦了。但最好的选择可能取决于它是否是真正的默认值:

option = 'default'
if condition1:
    option = 1
elif condition2:
    option = 2

或者只是另一种情况:

if z > 0:
    sign = 'positive'
elif z < 0:
    sign = 'negative'
else:
    sign = 'null'
© www.soinside.com 2019 - 2024. All rights reserved.