如果Python没有三元条件运算符,是否可以使用其他语言结构模拟一个?
有没有办法在Python中将if/ else语句压缩到一行?
我经常看到各种快捷方式,并怀疑它也适用于此.
可能重复:
在一行上放置一个简单的if-then语句
我正在处理一个python表达式,我想要压缩该表达式而不是使用if else语句.
s = [1, 2, 3, 4]
if len(s)>5:
print s.index(5)
else:
print 'cant print'
Run Code Online (Sandbox Code Playgroud)
有没有比使用else else语句更好的方法?
我知道条件表达式(或三元运算符)在Python中是懒惰的.它们代表条件执行而不是条件选择.换句话说,以下只有一个a或被b评估:
c = a if condition else b
Run Code Online (Sandbox Code Playgroud)
我有兴趣知道它是如何在内部实现的.Python是否转换if为如下所示的语句,如果是,则转换发生在什么阶段?
if condition:
c = a
else:
c = b
Run Code Online (Sandbox Code Playgroud)
或者三元运算符实际上是一个独立且独立的表达式,完全单独定义?如果是这样,我可以访问条件表达式的CPython代码吗?
我看这解释以下什么三元运营商的做法,但他们没有明确如何得到实施:
编辑:您可以假设CPython参考实现.
在java中,我使用
variable = something == 1 ? 1 : 0
Run Code Online (Sandbox Code Playgroud)
一直发挥作用。python中有等效的函数吗?
我想写一个语句,如果满足某个条件,则跳出 for 循环,但在一行中。
我知道这有效:
for val in "string":
if val == "i":
break
print(val)
Run Code Online (Sandbox Code Playgroud)
我知道这有效:
value_when_true if condition else value_when_false
Run Code Online (Sandbox Code Playgroud)
但是当我运行这段代码时,我收到了一个语法错误:
break if some_string[:5] == condition
Run Code Online (Sandbox Code Playgroud)
有没有办法在一行中写出这样的中断条件?我可能做错了什么吗?
谢谢!
def setBoolean(status):
if status:
status = False
else:
status = True
status = True
setBoolean(status)
Run Code Online (Sandbox Code Playgroud)
我想要一个按钮单击以将变量设置为 False 如果为 True,如果为 False,则为 True,即与它相反。我如何用最短的代码长度做到这一点?
我是 Pytorch 的初学者,想将这个语句作为一个整体输入 if else 语句:-
torch.device('cuda' if torch.cuda.is_available() else 'cpu')
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我吗?
我是一名中学生,刚刚开始学习函数。这段代码是关于指数的,但我不能使用导入数学。有没有办法使这段代码成为单行代码或使其更短?
def power(a, n):
x = 1
if n == 0:
print(1)
elif n > 0:
for i in range(n):
x = x * a
else:
for i in range(-n):
x = x * a
return x
print(power(2, 5))
Run Code Online (Sandbox Code Playgroud) 我认为 Python 支持单行 if 语句,但+=在 Leetcode 和 Repl 上出现错误。双线一号有效,所以我在这里主要是为了弄清楚 Python 的内部工作原理。
基于这个问题,我认为这会奏效。我想知道这是 Python 还是平台(Leetcode 或 Replit)问题。
这是我粘贴在下面以供后代使用的replit代码。
class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for num in nums:
count += 1 if len(str(num)) % 2 == 0
return count
nums = [12,345,2,6,7896]
s = Solution()
print(s.findNumbers(nums))
Run Code Online (Sandbox Code Playgroud)
我的错误是:
File "main.py", line 8
count += 1 if len(str(num)) % 2 == 0
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud) 如何打印文本“值除以3”而不是数字?我有一个范围(25,50),我想打印所有值,但如果值除以 3,我想得到一个文本而不是数字。
for s in range(25,50):
print(s)
if s % 3 == 0:
print(f'value {s} divide by 3')
Run Code Online (Sandbox Code Playgroud)
我想得到输出:
25
26
value 27 divide by 3
28
29
value 30 divide by 3
31
32
value 33 divide by 3
Run Code Online (Sandbox Code Playgroud)