首页 > 解决方案 > += 运算符可以在 Python 中的单行 if 语句中使用吗?

问题描述

我认为 Python 支持单行 if 语句,但+=在 Leetcode 和 Repl 上都出现错误。双线一号有效,所以我在这里主要是为了弄清楚 Python 的内部工作原理。

基于这个问题,我认为这会起作用。我想知道这是 Python 还是平台(Leetcode 或 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))

我的错误是:

File "main.py", line 8
    count += 1 if len(str(num)) % 2 == 0
                                       ^
SyntaxError: invalid syntax

标签: pythonpython-3.xif-statement

解决方案


当然!把它变成这样:

count += 1 if len(str(num)) % 2 == 0 else 0

你需要完成整个陈述。

1 if len(str(num)) % 2 == 0需要有确定的价值。添加0对您来说就足够了,但请注意,这并不总是可能的。请记住,这不是一个if声明,而是一个ternary operator,这是两个不同的东西。


推荐阅读