+=运算符可以在Python中的单行if语句中使用吗?

我认为 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))

我的错误是:

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

回答

当然!把它变成这样:

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

你需要完成整个陈述。

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


以上是+=运算符可以在Python中的单行if语句中使用吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>