计数器类对象到可用lis

2024-04-25 14:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了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]))

Tags: thetofromimportcountervalelementssort
2条回答

您可以将它们转换为列表,然后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

您应该只构建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)]

相关问题 更多 >