Python 默认值和基于其他变量设置值。如果否则或不。
有时我想将一个变量默认为某个值,如果设置了其他值,则将其更改为其他值。
问题是。什么是首选?设置默认值,然后在满足条件时更改它,或者根据添加的 else 进行初始检查仅设置一次条件?
代码中的示例。
if x:
y = '%s-other' % x
else:
y = 'some_default'
另一种选择是。
y = 'some_default'
if x:
y = '%s-other' % x
这并不总是传递给函数的参数,因此 kwargs 不是我想在这里依赖的东西。
就我个人而言,第二个对我来说似乎更清楚,但我还没有找到任何人对此的任何意见。
At times I have a variable that I want to default to something and if something else is set change it to something else.
The question is. What is preferred? Setting the default value and then changing it if the condition is met or setting the condition only once depending on the initial check with an added else?
Example in code.
if x:
y = '%s-other' % x
else:
y = 'some_default'
The other option would be.
y = 'some_default'
if x:
y = '%s-other' % x
This isn't always an argument passed in to a function so kwargs is not something I want to rely on here.
Personally, the second one seems to be a lot more clear to me but what I have yet to find any sort of opinion by anyone on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个怎么样:
How about this:
正如 Rob 指出的那样,
这是跨各种语言的非常常见的构造
Python 提供了更多替代方案,选择取决于用户
如果您正在处理字典,它已经有两个选项
x.setdefault(some_key,some_default )=other
您发布的其他内容也有效,但不是很 Pythonic,但您会遇到很多带有引用样式的代码。
对我来说,只要一个程序是可读的、高效的,我们就不应该太陷入Python化的结构中,这常常会偏离焦点。
As Rob pointed out,
is a very common construct across various language
Python provides some more alternatives and the choice depends on the User
If you are dealing with dictionary, it already has two options
x.setdefault(some_key,some_default)=other
The other's you posted are also valid but not very pythonic but yet you will encounter lot of code with your quoted style.
To me, as long as a program is readable, efficient, we should not be too bogged down to make some contruct pythonic which often deviates the focus.
对其他答案加更多糖:
但这一个可能会吓到人们,所以我建议使用罗布的答案:)
More sugar to other answers:
But this one may scare people so I'd recomend to use Rob's one :)
其他答案都没有涉及更一般的
if-elif-else
情况。当只有一个条件时,条件表达式正如其他答案指出的那样,这可能是最好的方法:
但如果有两个或多个条件,它就会变得很麻烦。但最好的选择可能取决于它是否是真正的默认值:
或者只是另一种情况:
None of the other answers deal with the more general
if-elif-else
case.When there's only one condition the conditional expression is probably the best way to go, as other answers pointed out:
But if there are two or more conditions it becomes cumbersome. But the best option there may depend if it is a true default:
or simply another case: