【问题标题】:syntax_error:update for dictionary语法错误:更新字典
【发布时间】:2016-05-29 06:15:57
【问题描述】:

我该如何解决这个问题?

# E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclusion in the dict (with "if word in dict"-style syntax).
# Or add it to the dict with something like word_dict[word] = 1.
def word_count(string):
    word_list = string.split()
    word_dict = {}
    for word in word_list:
        if word in word_dict:
            word_dict.update(word:word_dict(word)+1)
        else:
            word_dict[word]=1
    return word_dict

免责声明:Python 新手

【问题讨论】:

    标签: python string dictionary


    【解决方案1】:

    要更新字典中的键,只需使用[...] 订阅语法分配给键:

    word_dict[word] = word_dict[word] + 1
    

    甚至

    word_dict[word] += 1
    

    您的尝试不是有效的语法,原因有两个:

    • word_dict.update() 是一个方法调用,(...) 调用语法中的所有内容都必须是有效的表达式。 key: value 不是独立表达式,它仅在 {key: value} 字典显示中有效。 word_dict.update() 采用字典对象或 (key, value) 对的序列。
    • word_dict(word) 会尝试调用字典,而不是尝试检索键 word 的值。

    使用word_dict.update() 仅更新 一个 键有点过头了,因为它需要创建另一个字典或序列。以下任一方法都可以:

    word_dict.update({word: word_dict[word] + 1})
    

    word_dict.update([(word, word_dict[word] + 1)])
    

    请注意,Python 标准库附带了一个更好的单词计数解决方案:collections.Counter() class

    from collections import Counter
    
    def word_count(string):
        return Counter(string.split())
    

    Counter()dict 的子类。

    【讨论】:

    • 如何使用 .update() 编写该行?谢谢你的回答:)
    • 如果受访者使用from collections import Counter def word_count(string): return Counter(string.split()) 可以接受吗?面试中可接受的语言使用水平是多少?感谢您的提示
    • @MonaJalal:我想说它展示了对标准库的熟悉程度。如果他们知道Counter() 的所有功能,我还会进一步调查,询问也许可以用它做些什么,或者要求向我演示如何在没有Counter() 的情况下做同样的事情来探究基本的 Python 知识.这完全取决于你面试的职位。
    【解决方案2】:

    您可以使用dict.update 来实现。这是dict.update的示例

    In [74]: test_dict = {1:'apple',2:'grapes'}
    In [75]: test_dict.update({3:'orange'})
    In [76]: test_dict
    Out[76]: {1: 'apple', 2: 'test', 3: 'orange'}
    

    对于您的问题,将您的代码更改为 word_dict.update(word:word_dict(word)+1) to word_dict.update({word:word_dict(word)+1})

    这是reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多