2013-05-13 75 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})