python - += 运算符可以在 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
解决方案
当然!把它变成这样:
count += 1 if len(str(num)) % 2 == 0 else 0
你需要完成整个陈述。
1 if len(str(num)) % 2 == 0
需要有确定的价值。添加0
对您来说就足够了,但请注意,这并不总是可能的。请记住,这不是一个if
声明,而是一个ternary operator
,这是两个不同的东西。
推荐阅读
- android - READ_EXTERNAL_STORAGE 是指存储在应用程序沙箱或 SD 卡之外吗?
- .net - 调试:可以在我构建控制台应用程序时加载符号,但不能在我的应用程序附加到进程时加载
- git - 部署到 Heroku 按钮如何用于私人回购?
- html - 我在这个 Google 表单中找不到条目名称 (name=entry)
- html - 如何停止 div 的重叠?
- excel - 满足下一个空白单元格条件时中止宏
- python - 如何使用 Pandas 基于键创建数据框列的链接数组?
- angular - 如何在 ngFor 中为 mat-expansion-panel 做参考
- javascript - D3.js 饼图未显示所有弧线
- css - Angular ngx-dropzone 自定义 css