如何将计数器集合转换为列表

问题描述 投票:0回答:3

我需要将计数器集合的输出转换为列表

我的计数器输出是:

Counter({2017: 102, 2018: 95, 2015: 87,})

我想把它转换成这样的东西:

[[year,count],[year,count],[year,count]]
python list counter
3个回答
4
投票

使用
Counter(...).items()

from collections import Counter

cnt = Counter({2017: 102, 2018: 95, 2015: 87})

print(cnt.items())
>>> dict_items([(2017, 102), (2018, 95), (2015, 87)])

您可以将其转换为您想要的格式:

your_list = [list(i) for i in cnt.items()]

print(your_list)
>>> [[2017, 102], [2018, 95], [2015, 87]]

0
投票

您可以使用

most_common()
Counter
方法来生成一起显示值的元组列表

c = Counter({2017: 102, 2018: 95, 2015: 87,})
m = c.most_common()
print(m)

>>> [(2017, 102), (2018, 95), (2015, 87)]

您可以通过执行以下操作将结果转换为列表列表而不是元组:

print([list(i) for i in c.items()])

-1
投票

在这个例子中,我想将mis集合转换为列表,然后转换为df,所以我这样做了

lista_conteos = [list(i) for i in n_palabra.items()]
palabras = []
conteos = []
for i in range(0, len(lista_conteos)):
    palabras.append(lista_conteos[i][0][0])
    conteos.append(lista_conteos[i][1])
© www.soinside.com 2019 - 2024. All rights reserved.