0

好的,所以我正在导入 CSV,然后我想将所有迭代值row[0]row[1].

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

然后是甜菜菠萝等

4

2 回答 2

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')]
于 2012-07-02T18:27:18.893 回答
0
csvfile = csv.reader(open(filename, 'rb'), delimiter=',')

combinations = []

for rowa in csvfile:
    for rowb in csvfile:
        combinations.append(rowa[0] + ' ' + rowb[1])
于 2012-07-02T18:21:06.603 回答