【问题标题】:Create a new dictionary list from other lists?从其他列表创建一个新的字典列表?
【发布时间】:2020-02-10 17:26:33
【问题描述】:

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

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

【问题讨论】:

  • 你的字典从哪里来。最终类型是List[Dict[str, Dict[str, int]]]?我认为您需要确切了解您想要的类型。我相信你真的想要Dict[str, Dict[str, int]]
  • 你想要的输出大多是荒谬的,因为你不能有像 ['aaa':2] 这样的东西(它是一个像字典一样的带有键和值的列表)。如果我们实际上无法说出您想要的输出是什么,我不确定我们是否可以回答这个问题。您需要弄清楚在每个嵌套级别需要什么数据结构。您可以只使用两个级别的字典,但也许您想在某个地方放置列表,但我不知道在哪里。

标签: python list dictionary count


【解决方案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}}

【讨论】:

    【解决方案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,但它的工作方式有点不同。

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多