FreqDist 输出的列表列表
我使用了 FreqDist 来统计一个元组列表中每个元组出现的频率。得到的频率分布看起来是这样的:
<FreqDist: (1, 3): 3, (1, 4):2, (1, 2): 1...etc.
我想生成一个列表的列表,让输出看起来像这样:
[[1,3,3], [1,4,2], [1,2,1]...
我尝试了以下方法,但没有成功。
list3 = []
for key in combofreqdict:
temp = list(key)
temp.extend(value)
list3.append(temp)
有没有什么好主意?
2 个回答
0
如果频率分布(FreqDist)可以变成字典,或者它的表现像字典一样,那么你可以这样做:
import collections
# I used ordered dictionary as example, just to have the same order of items
# as in your question.
list1 = collections.OrderedDict([((1,3),3), ((1, 4),2), ((1, 2), 1)])
list3 = [list(k)+[v] for k,v in list1.items() ]
print(list3)
# [[1, 3, 3], [1, 4, 2], [1, 2, 1]]
顺便提一下,不要把列表命名为 list
。这样会覆盖掉内置的 list()
函数。
0
也许可以试试这样的方法:
print combofreqlist #<FreqDist: (1, 1): 2, (1, 3): 2, (1, 4): 2, (1, 5): 2, (2, 1): 1, (2, 5): 1, (3, 2): 1, (3, 3): 1, (4, 2): 1, (4, 5): 1, ...>
list3 = [list(k)+[v] for k,v in combofeqlist.items()]
print list3 #[[1, 1, 2], [1, 3, 2], [1, 4, 2], [1, 5, 2], [2, 1, 1], [2, 5, 1], [3, 2, 1], [3, 3, 1], [4, 2, 1], [4, 5, 1], [5, 2, 1]]
这个方法使用了 FreqDist
的 .items()
,然后通过把元组和最后一个项目连接在一起的方式来组合它们。