python-二维列表转换为字典并统计词频

在学习过程中经常会遇到列表转字典的问题,现提供一种方法供参考:
目的:将二位列表转换为一维列表,再将一维列表转换为字典斌统计词频。

from collections import Counter 
data=[[1,2,4,6,2],[8,9,4,6,2],[6,0,9,3,4]] 
a= eval('[%s]'%repr(data).replace('[', '').replace(']', ''))  
data=dict(Counter(a))
#--------------------------------------------------------
In [8]: a
Out[8]: [1, 2, 4, 6, 2, 8, 9, 4, 6, 2, 6, 0, 9, 3, 4]
In [9]: data
Out[9]: {0: 1, 1: 1, 2: 3, 3: 1, 4: 3, 6: 3, 8: 1, 9: 2}

猜你喜欢

转载自blog.csdn.net/zztingfeng/article/details/80330389
今日推荐