累计计算列表中每个元素的出现次数
Count cumulatively the occurrences of each element of a list
我有一个列表:
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']}
我错过了什么?
这是一个简单的解决方案示例:
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)
我有一个列表:
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']}
我错过了什么?
这是一个简单的解决方案示例:
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)