【问题标题】:Counting the frequency of a list of XML values计算 XML 值列表的频率
【发布时间】:2020-03-10 12:20:39
【问题描述】:

我在 Python 中使用以下代码从讨论列表中获取唯一用户 ID 的计数:


import xml.etree.ElementTree as ET
tree = ET.parse('Combined.xml')
root = tree.getroot()

for node in tree.findall('.//discussions/discussion/userid'):
    print (node.text)


print (len(tree.getroot().findall('.//discussions/discussion/userid'))) 
unique_list = [] 


for x in tree.getroot().findall('.//discussions/discussion/userid'): 
        if x not in tree.getroot().findall('.//discussions/discussion/userid'): 
            unique_list.append(x) 
for x in unique_list: 
        print ("The unique list is: ", x, end="") 

我收到以下输出:

... 16055 16055 16059 1760 22519 16055 21961 16790 13764 13779 13764 18601 18398 16790 25092 154

有什么方法可以计算此列表中唯一值的出现频率? (例如,16055 : 2、16059: 1 等...)

任何帮助将不胜感激...鲍勃

【问题讨论】:

    标签: python list frequency counting


    【解决方案1】:

    要生成一个计数器,你可以生成一个字典并增加它的计数器:

    count_dict = {}
    
    for x in tree.getroot().findall('.//discussions/discussion/userid'):
            if x not in unique_list:
                unique_list.append(x)
                count_dict[x] = 1
            else:
                count_dict[x] = count_dict[x] + 1
    

    【讨论】:

    • 您好,感谢您的意见。当我运行此代码时,我得到 而不是用户 ID 及其计数
    【解决方案2】:

    Counter 在这里可以很好地工作:

    from collections import Counter
    
    c = Counter(tree.getroot().findall('.//discussions/discussion/userid'))
    

    原因是Counter 是基于dict,它有唯一的键

    【讨论】:

      【解决方案3】:

      您可以为此目的使用 Python 字典:

      id_count = {}
      for u in unique_list:
          if u in id_count:
              id_count[u] += 1
          else:
              id_count[u] = 1
      

      【讨论】:

        猜你喜欢
        • 2015-11-20
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        相关资源
        最近更新 更多