【问题标题】:Adding for loops to dictionaries在字典中添加 for 循环
【发布时间】:2012-06-16 05:44:10
【问题描述】:

我在将 for 循环答案插入列表时遇到问题:

 for i in word_list:
        if i in word_dict:
            word_dict[i] +=1
        else:
            word_dict[i] = 1
print word_dict

有了这个,我得到了像这样的字数字典

{'red':4,'blue':3}
{'yellow':2,'white':1}

是否有可能以某种方式将这些答案添加到类似列表中

 [{'red':4,'blue':3},{'yellow':2,'white':1}]

基本上我从一个 for 循环中得到 5 个字典,是否可以将所有这些字典放入一个列表中,而无需更改每个字典。每次我尝试将它们放入一个列表时,它都会给我类似的信息:

[{{'red':4,'blue':3}]
[{'yellow':2,'white':1}]
[{etc.}]

http://pastebin.com/60rvcYhb

这是我的程序的副本,没有我用来编码的文本文件,基本上,books.txt 只包含来自 5 个作者的 5 个不同的 txt 文件,而且我在我掌握所有这些文件的字数的地方在我想添加到一个列表中的单独字典中,例如:

 [{'red':4,'blue':3},{'yellow':2,'white':1}]

【问题讨论】:

    标签: python list dictionary for-loop python-2.7


    【解决方案1】:
    word_dict_list = []
    
    for word_list in word_lists:
        word_dict = {}
        for i in word_list:
            if i in word_dict:
                word_dict[i] +=1
            else:
                word_dict[i] = 1
        word_dict_list.append(word_dict)
    

    或者简单地说:

    from collections import Counter
    word_dict_list = [ dict(Counter(word_list)) for word_list in word_lists]
    

    示例:

    from collections import Counter
    word_lists = [['red', 'red', 'blue'], ['yellow', 'yellow', 'white']]
    word_dict_list = [ dict(Counter(word_list)) for word_list in word_lists]
    # word_dict_list == [{'blue': 1, 'red': 2}, {'white': 1, 'yellow': 2}]
    

    【讨论】:

    • +1 尽管您应该将它们保留为 Counter。我认为没有必要将它们转换回来。
    • 看到我的问题是我的实际字数是段落,当我进行第一次测试时,它会将每个字典放入自己的列表中,例如:[{'red':3,'blue:2 }] [{'黄色':4,'白色':5}]
    • @DylanWard - 将这些信息放入问题中会很有帮助。
    • 好吧,我在 5 个单独的字典中得到了我的 for 循环答案。是否可以将所有这些字典放入一个列表中,而每个字典仍然是自己的?
    猜你喜欢
    • 2017-08-23
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多