【问题标题】:Python is not recognizing null in a listPython 无法识别列表中的空值
【发布时间】:2020-12-17 04:41:51
【问题描述】:

我是 Python 新手,我有一个问题。我应该在第 5 行放什么?我想看看字符 c 是否在组中不存在,然后我想创建一个并将其分配为 0。然后,将其增加到该字符出现的数量

def firstUniqChar(self, s):

    groups = {}
    for i in range(0, len(s) - 1):
        c = s[i]
        if groups[c] == null:
            groups[c] = 0
        else:
            groups[c] = groups[c] + 1
    for j in range(0, len(s) - 1):
        if groups[s[i]] == 1:
            return j
    return -1 

【问题讨论】:

  • c not in groups?或者groups.get(c) is None - Python 没有null
  • groups[c] 对于不存在的c 键将引发错误。如果键 c 不存在,则使用 groups.get(c, None) 默认为 None
  • groups.get(c) 将默认返回None,如果密钥不存在。
  • 好的,非常感谢。

标签: python list null numbers syntax-error


【解决方案1】:

你需要在python中写None而不是null。

你可以这样写

if groups[c] is None:

【讨论】:

  • 如果 c 不在组中 -> 例外
  • 比你必须处理的异常。您可以查找尝试除外。 link
  • 你没抓住重点 - 整篇文章是关于 c 不在组中,然后将其添加为计数为 0 的新键。
猜你喜欢
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多