2012-11-20 5 views
1

는의는어떻게 파이썬을 사용하여 쌍을 찾을 수 있습니까?

1 10,11,15 
2 12 
3 12,11 
4 10,11 

가 어떻게 목록을 반복하고 두 번째 열에서 객체의 가장 인기있는 쌍을 셀 수 (탭으로 구분 된 가정) 나는이 형식의 데이터가 있다고 가정하자? 두 번째 열에는 항목 수가 무제한 일 수 있다고 가정합니다. 파이썬 2.7이있는 경우

하는 Counter 조합 시도 :

이상적인 출력이 모두 당신이 목록의 목록에 입력을 얻을 수있는 가정을

pairs count 
10,11 (2) 
10,15 (1) 
11,15 (1) 
11,12 (1) 
+0

'list'처럼 보이지 않는? –

+0

숙제입니까? –

+1

왜 두 언어 태그가 필요합니까? –

답변

5

같은 것을 반환 itertools로 : 파이썬 < 2.6이있는 경우

>>> from collections import Counter 
>>> from itertools import combinations 
>>> l = [[10, 11, 15], [12], [12, 11], [10, 11]] 
>>> c = Counter(x for sub in l for x in combinations(sub, 2)) 
>>> for k, v in c.iteritems(): 
... print k, v 
... 
(10, 15) 1 
(11, 15) 1 
(10, 11) 2 
(12, 11) 1 

, 당신은,821,853,917을 사용할 수 있습니다과 조합 된(확실한 전문가의 한 사람이 깨끗한 해결책을 제공 할 것입니다).

In [1]: from collections import defaultdict 

In [2]: from itertools import combinations 

In [3]: l = [[10, 11, 15], [12], [12, 11], [10, 11]] 

In [4]: counts = defaultdict(int) 

In [5]: for x in l: 
    ...:  for item in combinations(x, 2): 
    ...:   counts[item] += 1 
    ...: 
    ...: 

In [6]: for k, v in counts.iteritems(): 
    ...:  print k, v 
    ...: 
    ...: 
(10, 15) 1 
(11, 15) 1 
(10, 11) 2 
(12, 11) 1 
0
In [7]: with open("data1.txt") as f: 
     lis=[map(int,x.split(",")) for x in f] 
    ...:  

In [8]: Counter(chain(*[combinations(x,2) for x in lis])) 
Out[8]: Counter({(10, 11): 2, (10, 15): 1, (11, 15): 1, (12, 11): 1}) 
0

당신은 combinationsCounter를 사용할 수 있습니다. `(10, 15) :

from itertools import combinations 
import collections 

newinput = [] 

# Removes the tabs 
for line in oldinput: 
    newinput.append(line.partition("\t")[2]) 

# set up the counter 
c = collections.Counter() 

for line in newinput: 
    # Split by comma 
    a = line.split(',') 
    # make into integers from string 
    a = map(int, a) 
    # add to counter 
    c.update(combinations(a, 2)) 

그런 다음, 당신은 당신의 카운트를 모두 가지고있는 Counter로 끝날 일) 등

관련 문제