Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:对列表列表执行计数操作_Python_List_Nested_N Gram - Fatal编程技术网

Python:对列表列表执行计数操作

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'], ['

我试图计算一大组文本中的bigram数。我已经从标准输入中逐行提取了文本,清理了文本,并由bigrams生成。现在我有了一个嵌套循环,它看起来像一行一行:

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)