如何在 Python 中从 C++/C# 紧密实现 ?: ?

发布于 2024-07-05 09:14:18 字数 195 浏览 6 评论 0原文

在 C# 中,我可以轻松地编写以下内容:

string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;

是否有一种快速方法可以在 Python 中执行相同的操作,或者我是否坚持使用“if”语句?

In C# I could easily write the following:

string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;

Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

快乐很简单 2024-07-12 09:14:18

顺便说一句,j0rd4n,您不会(不要!)在 C# 中编写这样的代码。 除了 IsDefaultOrNull 实际上被称为 IsNullOrEmpty 之外,这是纯粹的代码膨胀。 C# 为此类情况提供了合并运算符:

string stringValue = otherString ?? defaultString;

确实,只有当 otherStringnull (而不是空)时,这才有效,但如果可以事先确保这一点(并且通常是可以)它使代码更具可读性。

By the way, j0rd4n, you don't (please don't!) write code like this in C#. Apart from the fact that the IsDefaultOrNull is actually called IsNullOrEmpty, this is pure code bloat. C# offers the coalesce operator for situations like these:

string stringValue = otherString ?? defaultString;

It's true that this only works if otherString is null (rather than empty) but if this can be ensured beforehand (and often it can) it makes the code much more readable.

心不设防 2024-07-12 09:14:18

编写可读的、富有表现力的代码从来都不是坏事。

if otherString:
   stringValue = otherString
else:
   stringValue = defaultString

这种类型的代码更长、更具表现力,但也更具可读性,并且不太可能在路上被绊倒或误编辑。 不要害怕表达性地编写 - 可读的代码应该是一个目标,而不是副产品。

It's never a bad thing to write readable, expressive code.

if otherString:
   stringValue = otherString
else:
   stringValue = defaultString

This type of code is longer and more expressive, but also more readable and less likely to get tripped over or mis-edited down the road. Don't be afraid to write expressively - readable code should be a goal, not a byproduct.

吻安 2024-07-12 09:14:18

这个问题有一些重复,例如

本质上,在一般设置中,2.5 之前的代码应该使用这个:(

 (condExp and [thenExp] or [elseExp])[0]

给定 condExp、thenExp 和 elseExp 是任意表达式),因为如果 thenExp 计算结果为布尔值 False,它可以避免错误结果,同时保持短路计算。

There are a few duplicates of this question, e.g.

In essence, in a general setting pre-2.5 code should use this:

 (condExp and [thenExp] or [elseExp])[0]

(given condExp, thenExp and elseExp are arbitrary expressions), as it avoids wrong results if thenExp evaluates to boolean False, while maintaining short-circuit evaluation.

吾家有女初长成 2024-07-12 09:14:18

@担

如果是其他字符串: 
     字符串值 = 其他字符串 
  别的: 
     字符串值 = 默认字符串 
  

这种类型的代码更长、更具表现力,但也更具可读性

是的,它更长。 不太确定“更具表现力”和“更具可读性”。 至少,你的说法是有争议的。 我什至会说这是完全错误的,原因有两个。

首先,您的代码强调决策(相当极端)。 另一方面,条件运算符强调其他东西,即值(或所述值的赋值)。 这正是这段代码的作者想要的。 决策实际上是代码的副产品。 这里重要的部分是赋值操作。 您的代码将此分配隐藏在大量语法噪音中:分支。

您的代码表达能力较差,因为它转移了重要部分的重点。

即使这样,你的代码也可能胜过一些晦涩难懂的 ASCII 艺术,比如 ?:。 内联-if 会更好。 就我个人而言,我不喜欢 Python 2.5 引入的变体,因为它是向后的。 我更喜欢以与 C 三元运算符相同的流程(方向)读取但使用单词而不是 ASCII 字符的东西:

C = if cond then A else B

这毫无疑问会获胜。

不幸的是,C 和 C# 没有这样的表达性声明。 但是(这是第二个论点),C 语言的三元条件运算符已经建立了很长时间,以至于它本身已经成为一种习惯用法。 三元运算符与“传统”if 语句一样是语言的一部分。 因为它是一个习语,所以任何了解该语言的人都可以立即正确地阅读这段代码。 此外,它是表达这些语义的一种极其简短的方式。 事实上,这是可以想象的最短的方法。 它极具表现力,因为它不会用不必要的噪音掩盖本质。

最后,Jeff Atwood 对此写下了完美的结论: 最好的代码就是没有代码完全没有

@Dan

if otherString:
   stringValue = otherString
else:
   stringValue = defaultString

This type of code is longer and more expressive, but also more readable

Well yes, it's longer. Not so sure about “more expressive” and “more readable”. At the very least, your claim is disputable. I would even go as far as saying it's downright wrong, for two reasons.

First, your code emphasizes the decision-making (rather extremely). Onthe other hand, the conditional operator emphasizes something else, namely the value (resp. the assignment of said value). And this is exactly what the writer of this code wants. The decision-making is really rather a by-product of the code. The important part here is the assignment operation. Your code hides this assignment in a lot of syntactic noise: the branching.

Your code is less expressive because it shifts the emphasis from the important part.

Even then your code would probably trump some obscure ASCII art like ?:. An inline-if would be preferable. Personally, I don't like the variant introduced with Python 2.5 because it's backwards. I would prefer something that reads in the same flow (direction) as the C ternary operator but uses words instead of ASCII characters:

C = if cond then A else B

This wins hands down.

C and C# unfortunately don't have such an expressive statement. But (and this is the second argument), the ternary conditional operator of C languages is so long established that it has become an idiom in itself. The ternary operator is as much part of the language as the “conventional” if statement. Because it's an idiom, anybody who knows the language immediately reads this code right. Furthermore, it's an extremely short, concise way of expressing these semantics. In fact, it's the shortest imaginable way. It's extremely expressive because it doesn't obscure the essence with needless noise.

Finally, Jeff Atwood has written the perfect conclusion to this: The best code is no code at all.

心的位置 2024-07-12 09:14:18

在 Python 2.5 中,它

A if C else B

的行为很像 C 中的 ?: 。但是,它因两个原因而不受人欢迎:可读性,以及通常有更简单的方法来解决问题的事实。 例如,在你的情况下:

stringValue = otherString or defaultString

In Python 2.5, there is

A if C else B

which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:

stringValue = otherString or defaultString
痕至 2024-07-12 09:14:18

我还发现仅使用“或”运算符效果很好。 例如:

finalString = get_override() or defaultString

如果get_override()返回“”或None,它将始终使用defaultString

I also discovered that just using the "or" operator does pretty well. For instance:

finalString = get_override() or defaultString

If get_override() returns "" or None, it will always use defaultString.

我的奇迹 2024-07-12 09:14:18

diveintopython.net 第 4 章有答案。 这在 Python 中称为“与或”技巧。

Chapter 4 of diveintopython.net has the answer. It's called the and-or trick in Python.

蹲在坟头点根烟 2024-07-12 09:14:18

您可以利用逻辑表达式返回其值的事实,而不仅仅是 true 或 false 状态。 例如,您始终可以使用:

result = question and firstanswer or secondanswer

但需要注意的是,如果 firstanswer 为 false,则它不会像三元运算符那样工作。 这是因为问题首先被评估,假设它是真的,则返回第一个答案,除非第一个答案为假,所以这种用法不能像三元运算符一样起作用。 但是,如果您知道这些值,通常就不会有问题。 一个例子是:

result = choice == 7 and "Seven" or "Another Choice"

You can take advantage of the fact that logical expressions return their value, and not just true or false status. For example, you can always use:

result = question and firstanswer or secondanswer

With the caveat that it doesn't work like the ternary operator if firstanswer is false. This is because question is evaluated first, assuming it's true firstanswer is returned unless firstanswer is false, so this usage fails to act like the ternary operator. If you know the values, however, there is usually no problem. An example would be:

result = choice == 7 and "Seven" or "Another Choice"
满身野味 2024-07-12 09:14:18

如果您使用 ruby​​,您可以编写

stringValue = otherString.blank? ? defaultString : otherString;

内置的 blank? 方法,表示 null 或空。
快来吧,走向黑暗面吧……

If you used ruby, you could write

stringValue = otherString.blank? ? defaultString : otherString;

the built in blank? method means null or empty.
Come over to the dark side...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文