计数器类对象到可用列表

时间:2018-01-19 20:31:55

标签: python counter

我使用Counter类来获取迭代次数,现在我想将其格式化为:

from collections import Counter
elements = [1,6,9,4,1,2]
elements.sort()
Val=Counter(elements).keys() #Gives me all the values used : 1,2,4,6,9
Freq=Counter(elements).values() #Gives me the frequency : 2,1,1,1,1,
# I want display somethink like : 
# 1 : 2
# 2 : 1
# 4 : 1
# 6 : 1
# 9 : 1

#I have tried : but it is a dict Type : I need to convert this Val et Freq to List
for i in range(0,len(Val)):
    print(str(Val[i]) +" : "str(Freq[i]))

2 个答案:

答案 0 :(得分:2)

您应该只构建一次Counter。我们无法保证两个独立的Counter对象会以相同的顺序迭代它们的内容(对于大型输入,它只是无效)。

from collections import Counter

elements = [1,6,9,4,1,2]

for val, freq in sorted(Counter(elements).items()):
    print(val, ' : ', freq)

此处sorted(Counter(elements).items())是一个包含元组(val, freq)的排序列表:
[(1, 2), (2, 1), (4, 1), (6, 1), (9, 1)]

答案 1 :(得分:0)

您可以将它们转换为列表,然后zip将它们转换为

from collections import Counter
elements = [1,6,9,4,1,2]
elements.sort()
Val=list(Counter(elements).keys()) #Gives me all the values used : 1,2,4,6,9
Freq=list(Counter(elements).values()) #Gives me the frequency : 2,1,1,1,1,

for i,j in zip(Val,Freq):
    print(str(i) + ":" + str(j))

输出:

1:2
2:1
4:1
6:1
9:1