繁体   English   中英

从其他列表创建一个新的字典列表?

[英]Create a new dictionary list from other lists?

我有一个重复单词列表和另一个不重复单词列表如下(它们都位于 txt 文件中):

file1.txt:
listRepeat = ['aaa','aaa', 'bbb', 'ccc', 'ddd', 'bbb', 'ddd']

file2.txt:
listRepeat = ['aaa','eee', 'bbb', 'eee', 'bbb', 'ddd']

以及包含文件的非重复元素的以下列表:

listEND = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

我想创建一个字典列表如下:

[{'file1.txt':['aaa':2], ['bbb':2], ['ccc':1], ['ddd':2], ['eee':0]}]
[{'file2.txt':['aaa':1], ['bbb':2], ['ccc':0], ['ddd':1], ['eee':2]}]

这个想法是用文件列表的元素填充我的字典列表,并说出元素列表中这些元素的数量,就像上面的例子一样,但我没有正确构建这个字典。 我的代码如下所示:

for i in listEND:
        newllist.append({file:[i,listRepeat.count(i)]})

其中newlist是字典列表,它将相应的file作为字典键,并将元素及其各自的计数作为项放在i 但结果如下:

{'file1.txt': ['aaa', 2]}
{'file1.txt': ['bbb', 2]}
{'file1.txt': ['ccc', 1]}
...

等等。 有谁知道代码哪里错了?

尝试这个:

file1 = ['aaa','aaa', 'bbb', 'ccc', 'ddd', 'bbb', 'ddd']
file2 = ['aaa','eee', 'bbb', 'eee', 'bbb', 'ddd']

listEND = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

file_contents = {"file1.txt":file1, "file2.txt":file2}


new_list = {filename:{x:lst.count(x) for x in listEND} for filename, lst in file_contents.items()}
print(new_list)

输出:

{'file1.txt': {'aaa': 2, 'bbb': 2, 'ccc': 1, 'ddd': 2, 'eee': 0}, 'file2.txt': {'aaa': 1, 'bbb': 2, 'ccc': 0, 'ddd': 1, 'eee': 2}}

您想要的输出无效。 看起来您实际上想要嵌套的字典:

{'file1.txt': {'aaa': 2, 'bbb': 2, 'ccc': 1, 'ddd': 2, 'eee': 0},
 'file2.txt': {'aaa': 1, 'bbb': 2, 'ccc': 0, 'ddd': 1, 'eee': 2}}

在您的代码中实现这一点将如下所示:

...
for i in listEND:
    newdict[file][i] = listRepeat.count(i)

但在此步骤之前,您需要定义newdict = {}newdict[file] = {}


顺便说一句,您可以考虑使用collections.Counter代替,但它的工作方式略有不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM