我试图在这个python程序中读取一个csv文件作为列表。 test.csv文件只包含一行不同的数字。我想找到总和等于500的数字的可能组合,并在以列表形式输出后,python程序会将此列表附加到我的test.csv文件中。
csv_file.py
import sys
import csv
import os
file_name="test.csv"
path1 = "C:\MAYANK\python p"
path2 = os.path.join(path1, file_name)
with open(path2, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=",")
row1 = list(reader)
def subset_sum(numbers, target, partial=list()):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
with open(path2, 'a') as csv_file1:
writer = csv.writer(csv_file1)
writer.writerow(partial)
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i + 1:]
subset_sum(remaining, target, partial + [n])
if __name__ == '__main__':
subset_sum(row1, 500)
我已编写所有代码但收到此错误:
Traceback (most recent call last):
File "csv_file.py", line 33, in <module>
subset_sum(row1, 500)
File "csv_file.py", line 30, in subset_sum
subset_sum(remaining, target, partial + [n])
File "csv_file.py", line 17, in subset_sum
s = sum(partial)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
答案 0 :(得分:2)
with open(path2, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=",")
row1 = list(reader)
您的输入/您如何导入它是您的问题:
>>> subset_sum([111,222,333,444,555, 499, 1, 389, 20, 369], 500)
[111, 389]
[111, 20, 369]
[499, 1]
有效,同时:
>>> subset_sum([111,222,333,444,555, [499], 1, 389, 20, 369], 500)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
没有。
reader
必须是嵌套列表,然后sum([[]])
会TypeError: unsupported operand type(s) for +: 'int' and 'list'
,您可能会获得
TypeError: unsupported operand type(s) for +: 'int' and 'str'
这意味着您需要将该列表映射到整数。要解决此问题,请将list()
调用替换为map(int, )
:
with open(path2, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=",")
row1 = map(int, reader)
答案 1 :(得分:0)
list(reader)
为您提供行列表,其中每行都是字符串列表。换句话说,您的row1
是列表,而不是数字列表,这就是sum()
抛出该特定异常的原因。
您将其命名为row1
这一事实表明您只对第一行感兴趣。如果是这样,那么您实际上是想说row1 = list(reader)[0]
,这将为您提供sum()
可以处理的列表。但要注意,如果你这样做,你将失去对表格其余部分的访问权。
第二个问题是你需要将单个条目从字符串转换为数字,否则你不会得到你可能期望从sum()
获得的结果。
要在将整个表格从字符串转换为数字时保留整个表格,您可以这样做:
with open(path2, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=",")
table = [[float(x) for x in row] for row in reader]
row1 = table[0]
然后像以前一样继续。