计算列表中的共现次数

时间:2013-05-13 13:07:28

标签: python counting

我有一个由一组字符串列表组成的数组(可以假设每个字符串都是一个单词)。

我想在Python中有效地计算这个数组中的单词对。

它不是搭配或双字符串,因为该对中的每个单词可能位于列表中的任何位置。

2 个答案:

答案 0 :(得分: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']

答案 1 :(得分: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})