在配对列表中查找配对项的频率 [英] finding frequencies of pair items in a list of pairs

查看:58
本文介绍了在配对列表中查找配对项的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说一长串这种类型的东西:

Let's say I have a long list of this type:

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

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

Given the first elements, I want to construct a dictionary that would show a count of the second elements. For example in the particular example above, I'd like to have something like this:

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

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

Here's how I unsuccessfully tried to solve it. I constructed a list of unique first elements. Let's call it words and then:

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

我得到一个明显错误的结果.该代码的一个问题是,它对数过多.我不确定该如何解决.

I get an obviously erroneous result. One problem with the code is, it overcounts pairs. I am not sure how to solve this.

推荐答案

您应改为:

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]],即使pair[0]不是word,这也会将inner_dic分配给最后检查的pair中的第一个元素.

that is, you should be doing dic[word] rather than dic[pair[0]], which will assign the inner_dic to the first element in the last pair checked, even if pair[0] isn't word.

这篇关于在配对列表中查找配对项的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆