繁体   English   中英

简短的“if-else”的 Python 语句

[英]Python statement of short 'if-else'

C++ 中是否有以下if - else语句或类似语句的 Python 版本:

  int t = 0;
  int m = t==0?100:5;
m = 100 if t == 0 else 5 # Requires Python version >= 2.5
m = (5, 100)[t == 0]     # Or [5, 7][t == 0]

以上两行都会导致相同的结果。

第一行使用了自 2.5 版以来可用的 Python 版本的“三元运算符”,尽管 Python 文档将其称为Conditional Expressions

第二行是一个小技巧,以许多(所有重要的)方式提供内联功能,相当于在许多其他语言(例如CC++ )中找到的?:


Python文档- 5.11。 条件表达式

您所指的构造称为三元运算符 Python 有一个版本(从 2.5 版开始),如下所示:

x if a > b else y
t = 0
if t == 0:
  m = 100
else:
  m = 5

美丽总比丑陋好。
显式优于隐式。
简单胜于复杂。

来自PEP 20

或者,如果你真的,真的必须(在 Python >= 2.5 中工作):

t = 0
m = 100 if t == 0 else 5

还有:

m = t==0 and 100 or 5

由于 0 是一个假值,我们可以这样写:

m = t and 5 or 100

这相当于第一个。

我发现关键字传入中的第一个速记很方便。 下面的示例显示它在 tkinter 网格几何管理器中使用。

class Application(Frame):
    def rcExpansion(self, rows, cols, r_sticky, c_sticky):
        for r in range(rows):
            self.rowconfigure(r, weight=r)
            b = Button(self, text = f"Row {r}", bg=next(self.colors))
            b.grid(row=r, column= 0, sticky = N+S+E+W if r_sticky == True else None)
        for c in range(cols):
            self.columnconfigure(c, weight=c)
            b = Button(self, text = f"Column {c}", bg=next(self.colors))
            b.grid(row=rows, column = c, sticky = N+S+E+W if c_sticky == True else None)

app = Application(root=Tk())
app.rcExpansion(3, 4, True, False)

用于打印语句

a = input()

b = input()

print(a) if a > b else print(b)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM