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

时间:2020-02-10 17:26:33

标签: python list dictionary count

我有一个重复单词列表,另一个不重复单词列表如下(它们都位于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]}
...

,依此类推。有人知道代码中哪里有问题吗?

2 个答案:

答案 0 :(得分:2)

尝试一下:

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}}

答案 1 :(得分:0)

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

{'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,但是它的工作方式略有不同。