简体   繁体   English

Python嵌套列表解析,用于计算列表中相同字符串的出现次数

[英]Python nested list comprehension to count occurrences of same string across lists

I need to transform the following list: 我需要转换以下列表:

[
  [u'starred', u'review'],
  [u'starred', u'review'],
  [u'starred', u'review', u'pinned'],
  [u'starred'],
  [u'starred'],
  [u'starred', u'review']
]

into the following dict 进入下面的词典

{
  u'starred': 6,
  u'review': 4,
  u'pinned': 1
}

I've got the feeling that it should be possible by using list comprehension or a generator expression, but I'm not sure though. 我觉得应该可以使用列表理解或生成器表达式,但我不确定。

Any ideas? 有任何想法吗?

How about 怎么样

import itertools, collections
c = collections.Counter(itertools.chain(*your_list))

Flatten you list with generator expression and use collections.Counter : 用生成器表达式展平列表并使用collections.Counter

from collections import Counter

Counter(x for sub in L for x in sub)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM