简体   繁体   English

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

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

I have a list of repeated words and another list of words not repeated as follows (They are all located in txt files):我有一个重复单词列表和另一个不重复单词列表如下(它们都位于 txt 文件中):

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

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

and the following list that contains the non-repeated elements of the files:以及包含文件的非重复元素的以下列表:

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

I want to create a dictionary list as follows:我想创建一个字典列表如下:

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

The idea is to populate my dictionary list with the elements of the file lists and say the number of these elements in the list of elements, just like the example above, but I'm not getting the construction of this dictionary right.这个想法是用文件列表的元素填充我的字典列表,并说出元素列表中这些元素的数量,就像上面的例子一样,但我没有正确构建这个字典。 My code looks like this:我的代码如下所示:

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

Where the newlist is the dictionary list, where it places the respective file as the dictionary key and as items the elements and their respective count in i .其中newlist是字典列表,它将相应的file作为字典键,并将元素及其各自的计数作为项放在i But the result is this below:但结果如下:

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

and so on.等等。 Does anyone know where is wrong in the code?有谁知道代码哪里错了?

Try this:尝试这个:

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)

Output:输出:

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

Your desired output is invalid.您想要的输出无效。 It looks like you actually want nested dicts:看起来您实际上想要嵌套的字典:

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

Making that happen in your code would look like this:在您的代码中实现这一点将如下所示:

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

But before this step you'll need to define newdict = {} and newdict[file] = {} .但在此步骤之前,您需要定义newdict = {}newdict[file] = {}


BTW you could consider using collections.Counter instead, but it works a bit differently.顺便说一句,您可以考虑使用collections.Counter代替,但它的工作方式略有不同。

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

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