Python:对列表列表执行计数操作
我试图计算一大组文本中的bigram数。我已经从标准输入中逐行提取了文本,清理了文本,并由bigrams生成。现在我有了一个嵌套循环,它看起来像一行一行:Python:对列表列表执行计数操作,python,list,nested,n-gram,Python,List,Nested,N Gram,我试图计算一大组文本中的bigram数。我已经从标准输入中逐行提取了文本,清理了文本,并由bigrams生成。现在我有了一个嵌套循环,它看起来像一行一行: Input: [['breakfast', 'large'], ['large', 'portions'], ['portions', 'and'], ['friendly', 'staff']] [['highly', 'recommend'), ['recommend', 'coming'], ['coming', 'here'], ['
Input:
[['breakfast', 'large'], ['large', 'portions'], ['portions', 'and'], ['friendly', 'staff']]
[['highly', 'recommend'), ['recommend', 'coming'], ['coming', 'here'], ['here', 'excellent'], ['excellent', 'service']]
我想做的是将这些嵌套列表拆分为一行,这样我就可以使用
print ('%s\t%s' % (list(bigrams), 1))
这将提供逐行输出,例如:
Output:
['breakfast', 'large'], 1
['large', 'portions'], 1
['portions', 'and'], 1
可以将单个列表项转换为元组,然后比较元组。创建一个以元组作为键的字典来维护计数。Python将元组与其中的内容进行比较,因为元组是不可变的
count_dict= {}
for element in input_list:
element =tuple(element )
if(element in count_dict):
count_dict[a]+=1
else:
count_dict[a]=1
print(count_dict)