2013-05-13 30 views
0

我有一个由一组字符串列表组成的数组(可假定每个字符串都是一个单词)。统计列表中共现的数量

我想要一个有效的方式,在Python中,对这个数组中的单词对进行计数。

这不是搭配或二元组,因为这对中的每个单词可能位于列表上的任何位置。

+5

一组字符串在Python中不起作用(尽管我认为它可能不代表Python集合)。请举例 – jamylak 2013-05-13 13:08:08

+0

每个列表中有多少个字符串? – gnerkus 2013-05-13 13:13:01

+0

你能给我们一个你的清单的例子吗? – 2013-05-13 13:19:13

回答

0

目前还不清楚你的列表是怎么了,是不是这样的:

li = ['hello','bye','hi','good','bye','hello'] 

如果是这样的解决方案很简单:

In [1342]: [i for i in set(li) if li.count(i) > 1] 
Out[1342]: ['bye', 'hello'] 

否则,如果它是这样的:

li = [['hello'],['bye','hi','good'],['bye','hello']] 

然后:

In [1378]: f = [] 

In [1379]: for x in li: 
..........  for i in x: 
..........   f.append(i) 

In [1380]: f 
Out[1380]: ['hello', 'bye', 'hi', 'good', 'bye', 'hello'] 

In [1381]: [i for i in set(f) if f.count(i) > 1] 
Out[1381]: ['bye', 'hello'] 
0
>>> from itertools import chain 
>>> from collections import Counter 
>>> L = [['foo', 'bar'], ['apple', 'orange', 'mango'], ['bar']] 
>>> c = Counter(frozenset(x) for x in combinations(chain.from_iterable(L), r=2)) 
>>> c 
Counter({frozenset(['mango', 'bar']): 2, frozenset(['orange', 'bar']): 2, frozenset(['foo', 'bar']): 2, frozenset(['bar', 'apple']): 2, frozenset(['orange', 'apple']): 1, frozenset(['foo', 'apple']): 1, frozenset(['bar']): 1, frozenset(['orange', 'mango']): 1, frozenset(['foo', 'mango']): 1, frozenset(['mango', 'apple']): 1, frozenset(['orange', 'foo']): 1})