2012-07-02 110 views
0

好的,所以我導入了一個CSV,然後我想將row[0]中的所有迭代值與row[1]中的迭代值合併。合併CSV中兩個不同列的所有值

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

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

這樣,除了我希望所有的row[0]值的與所有的row[1]值的結合,即使他們不在同一行。

所以可以說我有兩列,一列是:

asparagus 
beets 
corn 
cucumbers 
tomatoes 

,另一個是:

pineapple 
orange 
apple 
raspberry 
blueberry 

我想有蘆筍所有列表2的組合,即:

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」,「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

這將遍歷'rowb' len(rowa)* len(rowb)'次。 – Blender

+0

@Blender結果大小爲O(n^2),運行時間如何低於那個? – xvatar

+0

對不起,我誤解了這個問題。我認爲OP正在考慮將兩行合併爲一行,而不是做出所有可能的組合。 – Blender

相關問題