为什么python字典不按我的预期工作?

时间:2019-11-29 17:34:51

标签: python python-3.x dictionary counting

try-catch

我需要将n个文本文件传递给程序并获取输出:

#!/usr/bin/env python3.7
import sys

def main():
    list_placeholder = [0 for _ in range(1, len(sys.argv))]
    dict_file_content = {}

    for arg_file in range(1, len(sys.argv)):
        content = ''
        with open(sys.argv[arg_file]) as f:
            for line in f:
                content += line
            dict_file_content[arg_file] = content

    dict_symbols = {}

    for key in dict_file_content:
        content = dict_file_content[key]
        for i in content:
            if dict_symbols.get(i) == None:
                dict_symbols[i] = list_placeholder

    for key in dict_file_content:
        content = dict_file_content[key]
        for key_symbol in dict_symbols:
            dict_symbols[key_symbol][key-1] = content.count(key_symbol)
    print(dict_symbols)

if __name__ == "__main__":
    main()

其中字典键是唯一字符,列表是该字符在文本中出现的次数,list [0] =第一个文本中出现的次数,list [1] =在文本中出现的次数第二个文字,等等。

1 个答案:

答案 0 :(得分:0)

您的dict_symbols引用了同一列表。您需要为每个条目提供自己的列表:

    for key in dict_file_content:
        content = dict_file_content[key]
        for i in content:
            if dict_symbols.get(i) == None:
                dict_symbols[i] = list_placeholder[:]

通知list_placeholder[:]复制。