CSV

2012-07-02 7 views
0

Ok에서 두 개의 다른 열의 모든 값을 결합하므로 CSV를 가져오고 난 다음 row[0]의 모든 반복 값과 row[1]의 반복 값을 결합하고자합니다. 나는 그들이 같은 행에없는 경우에도, row[1]의 모든 값과 결합 row[0]의 모든 값을 원하는 제외하고는 그와 같이CSV

csvfile = csv.reader(open(filename, 'rb'), delimiter=',') 

for row in csvfile: 
    row[0] + row[1] 

.

그래서, 한 열이 나는 두 개의 열이 있다고 할 수 있습니다 :

asparagus 
beets 
corn 
cucumbers 
tomatoes 

하고, 다른 하나는 :

pineapple 
orange 
apple 
raspberry 
blueberry 

내가 아스파라거스 목록 2의 ALL과 결합 갖고 싶어, 즉 : 사탕무 파인애플에에 다음

asparagus pineapple 
asparagus orange 
asparagus apple 
asparagus raspberry 
asparagus blueberry 

그리고

답변

2
In [1]: import csv 

In [2]: from itertools import product 

In [3]: csvfile = csv.reader(open('filename', 'rb'), delimiter=',') 

In [4]: list(product(*zip(*list(csvfile)))) 
Out[4]: 
[('asparagus', 'pineapple'), 
('asparagus', 'orange'), 
('asparagus', 'apple'), 
('asparagus', 'raspberry'), 
('asparagus', 'blueberry'), 
('beets', 'pineapple'), 
('beets', 'orange'), 
('beets', 'apple'), 
('beets', 'raspberry'), 
('beets', 'blueberry'), 
('corn', 'pineapple'), 
('corn', 'orange'), 
('corn', 'apple'), 
('corn', 'raspberry'), 
('corn', 'blueberry'), 
('cucumbers', 'pineapple'), 
('cucumbers', 'orange'), 
('cucumbers', 'apple'), 
('cucumbers', 'raspberry'), 
('cucumbers', 'blueberry'), 
('tomatoes', 'pineapple'), 
('tomatoes', 'orange'), 
('tomatoes', 'apple'), 
('tomatoes', 'raspberry'), 
('tomatoes', 'blueberry')] 
+0

예, 내 형식이 행에 없습니다. [[ "blah", "blah"], [ "two", "two,"two]] –

+0

@AndrewAlexander 문제를 아주 잘 이해하고 있습니다. 각 쌍을 문자열로 포맷해야합니까? –

+0

글쎄, 여전히 전체 목록을 반복해야합니까? –

0
csvfile = csv.reader(open(filename, 'rb'), delimiter=',') 

combinations = [] 

for rowa in csvfile: 
    for rowb in csvfile: 
     combinations.append(rowa[0] + ' ' + rowb[1]) 
+0

이렇게하면'rowen''len (rowa) * len (rowb)'횟수만큼 반복됩니다. – Blender

+0

@Blender 결과 크기는 O (n^2)입니다. 어떻게 실행 시간이 그보다 더 짧을 수 있습니까? – xvatar

+0

죄송합니다. 질문을 잘못 읽었습니다. 나는 OP가 두 행을 하나로 합쳐서 모든 가능한 조합을 만들기를 바라지 않는다고 생각했습니다. – Blender

관련 문제