【问题标题】:Python Dictionary value gets assigned into different keyPython字典值被分配到不同的键
【发布时间】:2016-02-13 09:24:01
【问题描述】:

我正在尝试在 python 中编写一个字数统计程序。为此,我使用字典来存储单词的数量。

字典的格式为 d[int] = [单词数组]。

添加单词时,如果单词已经存在于 dict 中,则删除该单词并附加到下一个键。

在执行 d[index].append(word) 时,它以某种方式被添加为新键。难道我做错了什么?我在 Ubuntu 上使用 python 3.4.3 和 2.7.9。

def count_words(s, n):
    d = {}
    d[1] = []
    word_array = []
    for word in s.split():
        if word not in word_array:
            d[1].append(word)
            word_array.append(word)
        else:
            keys = list(d.keys())
            for key in keys:
                if word in d[key]:
                    index = key+1
                    d[key].remove(word)
                    if index in d.keys():
                        print ('appending %s at %d on %s' % (word, index, d[index]))
                        d[index].append(word)
                        #print d[index]
                    else:
                        d[index] = list([word])
            print ('%s -> %s' % (word, d))
    print (d)

def test_run():
    """Test count_words() with some inputs."""
    count_words("cat bat mat cat bat cat", 3)
    #print count_words("betty bought a bit of butter but the butter was bitter", 3)
    #print count_words('london bridge is falling down falling down falling down london bridge is falling down my fair lady', 5)

if __name__ == '__main__':
    test_run()

【问题讨论】:

  • 顺便说一句,4 个空格缩进会使代码更具可读性; index in d.keys() -> index in d, list([word]) -> [word]
  • 你可以看看Counters。
  • 有更好的方法来解决这个问题。但是,这只是我为检查某些内容而创建的一次性代码。我的问题是这是一个错误还是编程问题?

标签: python python-2.7 python-3.x


【解决方案1】:

你的代码中的问题是你没有打破循环

for key in keys:
    if word in d[key]:
        code that removes word from d[key] and inserts it into d[key+1] list

在某个执行点字典d有以下内容

{1: ['bat', 'mat'], 2: ['cat']}

句子中的下一个单词是bat,所以你的代码是这样的:

    1234563
  1. 在第二次迭代中,它在 d[2] 中找到 bat,并继续在 d[3] 中删除和创建新列表。

word 附加到d[index] 后,您需要中断循环

http://ideone.com/sROy6m

【讨论】:

    【解决方案2】:

    我花了一段时间才意识到您使用的是哪种数据结构。颠倒顺序,使用collections.Counter来统计单词会更有效;如果您需要反向结构(也就是按计数计算的单词),您可以稍后构建它:

    from collections import Counter, defaultdict
    
    def words_by_count(s):
        word_counts = Counter(s.split())
        by_count = defaultdict(list)
        for word, count in word_counts.items():
            by_count[count].append(word)
    
        return by_count
    
    print(words_by_count('cat bat mat cat bat cat'))
    

    打印:

    defaultdict(<class 'list'>, {1: ['mat'], 2: ['bat'], 3: ['cat']})
    

    【讨论】:

    • 我同意,这只是我创建的用于检查某些内容的一次性代码。但是,我的问题是这是一个错误还是编程问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多