在特定情况下,我有这个清单:
[12112,7676,11708,6045,4705,11143,11143,5895]
并希望输出:
{"12112":"1","7676":"1","11708":"1","11143":"2","5895":"1","6045":"1","4705":"1"}
答案 0 :(得分:5)
您可以使用Counter
:
>>> from collections import Counter
>>> l = [12112,7676,11708,6045,4705,11143,11143,5895]
>>> Counter(l)
Counter({11143: 2, 4705: 1, 7676: 1, 5895: 1, 12112: 1, 11708: 1, 6045: 1})
如果你想要一个字典
>>> dict(Counter(l))
{12112: 1, 4705: 1, 11143: 2, 11708: 1, 5895: 1, 7676: 1, 6045: 1}
当你的问题使用字符串时,字典理解可以完成工作:
>>> {str(i):str(j) for i,j in Counter(l).items()}
{'12112': '1', '11143': '2', '4705': '1', '11708': '1', '5895': '1', '6045': '1', '7676': '1'}
因为你想要一个"
的字符串:
>>> re.sub(r'(\d+)',r'"\1"',str(dict(Counter(l))))
'{"12112": "1", "4705": "1", "11143": "2", "11708": "1", "5895": "1", "7676": "1", "6045": "1"}'
答案 1 :(得分:1)
您可以从列表中创建set
以确定唯一元素。然后使用带有count
的字典理解来确定列表中每个唯一元素的实例数。
>>> l = [12112,7676,11708,6045,4705,11143,11143,5895]
>>> {i : l.count(i) for i in set(l)}
{12112: 1, 4705: 1, 5895: 1, 11708: 1, 11143: 2, 7676: 1, 6045: 1}
否则您可以使用collections.Counter
>>> from collections import Counter
>>> dict(Counter(l))
{12112: 1, 4705: 1, 5895: 1, 11708: 1, 11143: 2, 7676: 1, 6045: 1}
答案 2 :(得分:1)
您也可以使用groupby
使用map
m= map(str,l)
然后groupby
,每个列表的长度描述频率。
m= map(str,l)
{key:str(len(list(group))) for key, group in groupby(m)}
您的代码看起来像
l = [12112,7676,11708,6045,4705,11143,11143,5895]
from itertools import groupby
print {key:str(len(list(group))) for key, group in groupby(map(str,l))}
输出:
{'12112': '1', '11143': '2', '4705': '1', '11708': '1', '5895': '1', '6045': '1', '7676': '1'}