【问题标题】:Count cumulatively the occurrences of each element of a list累计计算列表中每个元素的出现次数
【发布时间】:2020-08-07 10:46:54
【问题描述】:

我有一个清单:

selection_list=[3, 2, 3, 2, 2, 2]

我想累计计算每个元素的出现次数,我希望输出为:

['1/2', '1/4' , '2/2', '2/4', '3/4', '4/4'] # 1/2 means: first occurrence of two
dico={'selection':[], 'Number':[]}
l=[]
keys=[]
for i in range(len(selection_list)):
        dico['selection'].append(selection_list[i])
        #counting the total occurrences of each element
        occurrences = collections.Counter(selection_list)
for i in occurrences.keys():
        keys.append(i)
    #indexes of each element of the list 
for j in range(len(keys)):
       l.append([i for i,val in enumerate(selection_list) if val==keys[j]])
        

for i in range(len(l)):
       for j in l[i] :
       dico['Number'].insert(int(j), str(len(l[i]))+'-'+ str(len(l[i])) )

我得到这个输出:

dico={'selection': [2, 3, 2, 3, 3, 3], 'UnfoldingNumber': ['2-2', '4-4', '2-2', '4-4', '4-4', '4-4']}

我错过了什么?

【问题讨论】:

    标签: python python-3.x list indexing find-occurrences


    【解决方案1】:

    这是一个简单的解决方案示例:

    from collections import Counter
    
    selection_list=[3, 2, 3, 2, 2, 2]
    
    numerator = {i:0 for i in set(selection_list)}
    denominator = Counter(selection_list)
    
    result = []
    for v in selection_list:
        numerator[v] += 1
        result.append(str(numerator[v]) + '/' + str(denominator[v]))
    
    print(result)
    

    【讨论】:

      猜你喜欢
      • 2021-07-25
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 2011-08-10
      相关资源
      最近更新 更多