2015-01-23 2 views
0

열 1에서 중복을 제거하고 파이썬을 사용하여 각 고유 항목과 관련된 값의 관련 목록을 열 2로 반환하고 싶습니다.열에 중복 된 항목을 찾고 고유 항목을 반환하고 파이썬의 다른 열에서 해당 값을 나열하십시오.

입력은 출력

1 2 
Jack London 'Son of the Wolf, Chris Farrington, Able Seaman, The God of His Fathers,Children of the Frost' 
William Shakespeare 'The Rape of Lucrece,Venus and Adonis' 
Oscar Wilde 'Ravenna,Poems' 

이어야 동안

1 2 
Jack London 'Son of the Wolf' 
Jack London 'Chris Farrington' 
Jack London 'The God of His Fathers' 
Jack London 'Children of the Frost' 
William Shakespeare 'Venus and Adonis' 
William Shakespeare 'The Rape of Lucrece' 
Oscar Wilde 'Ravenna' 
Oscar Wilde 'Poems' 

여기서 각 아이템에 연관된 값의 합을 은닉 번째 열에. I 사전

dic={'Jack London': 'Son of the Wolf', 'Jack London': 'Chris Farrington', 'Jack London': 'The God of His Fathers'} 
set(dic) 

의 세트() 함수를 시도했지만 파이썬

set(['Jack London']) 
+0

어떻게 분할하는 열을? –

+0

@AdamSmith 나는 그것이 중요하다고 생각하지 않는다. 그는 입력을 분석하는 방법을 묻지 않는다. – augurar

+0

이 작업을 수행하는 코드를 작성하는 것은 유혹스러운 일이지만, 나는 당신이나 내가 그렇게 많은 것을 배울 것이라고 생각지 않습니다. 다음은 도움이 될만한 예제입니다. https://docs.python.org/2/library/collections.html#defaultdict-examples – spirulence

답변

2

목록이 정렬되어 있으므로 itertools.groupby을 사용해야합니다.

rows = [('1', '2'), 
     ('Jack London', 'Son of the Wolf'), 
     ('Jack London', 'Chris Farrington'), 
     ('Jack London', 'The God of His Fathers'), 
     ('Jack London', 'Children of the Frost'), 
     ('William Shakespeare', 'Venus and Adonis'), 
     ('William Shakespeare', 'The Rape of Lucrece'), 
     ('Oscar Wilde', 'Ravenna'), 
     ('Oscar Wilde', 'Poems')] 
# I'm not sure how you get here, but that's where you get 

from itertools import groupby 
from operator import itemgetter 

grouped = groupby(rows, itemgetter(0)) 
result = {group:', '.join([value[1] for value in values]) for group, values in grouped} 

이 당신의 결과 제공 :

In [1]: pprint(result) 
{'1': '2', 
'Jack London': 'Son of the Wolf, Chris Farrington, The God of His Fathers, ' 
       'Children of the Frost', 
'Oscar Wilde': 'Ravenna, Poems', 
'William Shakespeare': 'Venus and Adonis, The Rape of Lucrece'} 
+0

다음 결과가 원하는 사양에 더 가깝다고 생각합니다. result = {group : [x [1 :] [0] for x 값] 그룹, 값은 그룹화 됨} –

+0

@JimDennis True. 나는 아마도 data = {group : [col] 값에 대해 col [1]을 그룹화해야한다. result = "{} {}". 형식 (행 [0], ''데이터 행의 경우 행 [1 :])) ' –

+0

예, 기술적으로 그는 "출력은"이어야한다고 말합니다. 나는 그가 사실상의 결과보다는 결과적인 데이터 구조에 더 관심이 있다고 가정하고 있습니다. 나의 제안, 그리고 내가 업 그레 이드 한 augurar의 대답은 "결과물"에 대한 글자 그대로의 요청보다는 그의 질문에 대한 해석에 근거를두고있다. –

2

, 사전 전용 키마다 하나 개의 값을 포함 할 수있는 사전의 첫 번째 키를 반환. 그러나 값이 항목의 집합 일 수 있습니다

>>> d = {'Jack London': ['Son of the Wolf', 'Chris Farrington']} 
>>> d['Jack London'] 
['Son of the Wolf', 'Chris Farrington'] 

키 - 값 쌍의 순서에서 이러한 사전을 구성하려면, 다음과 같이 작업을 수행 할 수 있습니다

dct = {} 
for author, title in items: 
    if author not in dct: 
     # Create a new entry for the author 
     dct[author] = [title] 
    else: 
     # Add another item to the existing entry 
     dct[author].append(title) 

루프의 몸이 될 수 있습니다 다음과 같이 더 간결하게 작성했습니다.

dct = {} 
for author, title in items: 
    dct.setdefault(author, []).append(title) 
관련 문제