Python 输入文件csv与列表的itertools.composition
我有一个CSV文件(out.txt),格式如下Python 输入文件csv与列表的itertools.composition,python,list,combinations,itertools,Python,List,Combinations,Itertools,我有一个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:
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);
但是,如果我手动定义这样的数组
[1,2,3]
它返回正确的答案。如何处理列表
另外,如何将输出写入csv?您需要:
- 分别读每一行
- 对于每一行,获取组合(我在下面使用)
- 将iTerTools生成器列表的str表示形式打印到输出文件的一行中(从中删除)
- 添加换行符
- 对所有线路都这样做
”
:
with open ("data.txt","w") as f:
f.write("red,green,blue\nbanana,apple,orange")
# store each line as list of words seperately
lines = []
with open("data.txt") as f:
for l in f:
l = l.strip() # remove \n
if l:
lines.append( list(w.strip() for w in l.split(",")))
print(lines) # [['red', 'green', 'blue'], ['banana', 'apple', 'orange']]
from itertools import combinations
with open("result.txt", "w") as f:
for l in lines:
for c in combinations(l,2):
f.write(str(list(c)).replace("'","")) # remove the ' of strings
f.write("\n")
print(open("result.txt").read())
输出:
# what was read into `lines` from the file
[['red', 'green', 'blue'], ['banana', 'apple', 'orange']]
# output for 'result.txt'
[red, green][red, blue][green, blue]
[banana, apple][banana, orange][apple, orange]
您发布的代码中充满了缩进错误-请修复它以及为什么是“;”在每行的末尾?好的,但不是流行的Python风格。希望能修复代码。对不起,我是一个完全的初学者,我会仔细阅读的。我主要来自PHP背景。哇,这就是我想要的。还有一个问题。如果result.txt包含一些重复项,如[red,green][red,blue][green,blue][apple,orange][red,green][red,blue][red.purple],请注意[red,green]是重复项。如何删除[red,green]或仅获取唯一值?@Sam使用上面的代码,除非在输入中获得相同的值,否则不会获得任何重复项。该代码不考虑“其他输入行”-调整此代码以从输入中删除重复值可以使用集合或其他方法完成,但您也可以删除“红、绿、蓝、红”第二个红色值-您必须以某种方式从
行的内部列表中删除被复制的值
-关于从列表中删除重复的内容有很多帖子-例如,您必须测试多行,使其更加困难-尽最大努力或问一个新问题,集中于该问题在研究之后,你发现了什么
# what was read into `lines` from the file
[['red', 'green', 'blue'], ['banana', 'apple', 'orange']]
# output for 'result.txt'
[red, green][red, blue][green, blue]
[banana, apple][banana, orange][apple, orange]