gpt4 book ai didi

python - 在成对列表中查找成对项目的频率

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:53 24 4
gpt4 key购买 nike

假设我有一个很长的这种类型的列表:

text = [ ['a', 'b'], ['a', 'd'], ['w', 'a'], ['a', 'b'], ... ]

鉴于第一个元素,我想构建一个字典来显示第二个元素的计数。例如在上面的特定示例中,我想要这样的东西:

{'a': {'b':2, 'd':1},
'w': {'a':1}
}

这是我尝试解决它但未成功的方法。我构建了一个独特的第一元素列表。我们称它为 words 然后:

dic = {}

for word in words:
inner_dic = {}
for pair in text:
if pair[0] == word:
num = text.count(pair)
inner_dic[pair[1]] = num
dic[pair[0]] = inner_dic

我得到一个明显错误的结果。代码的一个问题是,它多算了对。我不确定如何解决这个问题。

最佳答案

你应该这样做:

for word in words:
inner_dic = {}
for pair in text:
if pair[0] == word:
num = text.count(pair)
inner_dic[pair[1]] = num
dic[word] = inner_dic

也就是说,您应该执行 dic[word] 而不是 dic[pair[0]],后者将分配 inner_dic到检查的最后一个 中的第一个元素,即使 pair[0] 不是 word

关于python - 在成对列表中查找成对项目的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28528105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com