【发布时间】:2020-04-05 12:40:20
【问题描述】:
我有一个 CSV 文件 (out.txt),格式如下
red,green,blue
banana,apple,orange
我正在尝试生成所有两种组合,以便将输出放入 output.csv,如下所示
[red,green][red,blue][green,blue]
[banana,apple][banana,orange][apple,orange]
我的单行代码是
import csv
with open('out.txt', newline='') as csvfile:
csvdata = list(csv.reader(csvfile))
print(csvdata)
r = 2;
n = len(csvdata);
print(n)
def printCombination(csvdata, n, r):
data = [0]*r;
print (data)
combinationUtil(csvdata, data, 0,
n - 1, 0, r);
def combinationUtil(csvdata, data, start,
end, index, r):
if (index == r):
for j in range(r):
print(data[j], end = " ");
print();
return;
i = start;
while(i <= end and end - i + 1 >= r - index):
data[index] = csvdata[i];
combinationUtil(csvdata, data, i + 1,
end, index + 1, r);
i += 1;
printCombination(csvdata, n, r);
csvdata 打印为
[['red', 'green', 'blue'], ['banana', 'apple', 'orange']]
但是,如果我像这样手动定义一个数组
[1,2,3]
它返回正确的答案。我该如何处理列表?
我如何将输出写入 csv ?
【问题讨论】:
-
您发布的代码充满了
IndentationError's - 请edit 修复它 -
还有为什么是';'在每一行的末尾?好的,但不是流行的 Python 风格。
-
希望修复代码。对不起,我是一个完整的初学者,我会阅读这个。我主要来自 PHP 背景。
标签: python list combinations itertools