第A部分:我被要求从包含2列的csv文件中读取数据,并在元组中返回数据。
B部分:使用csv文件返回的数据,我需要对每对元组求和:
来自A部分:
def csvReader(filename): #Function for reading .csv file
with open(filename) as file:
reader = csv.reader(file, delimiter=' ')
next(reader, None)
data = [tuple(row) for row in reader]
return(data)
csvReader('data.csv')
以下是我从A部分返回的内容:
[('60,','20,'(,('100,','%5,'
来自B部分:
def Plot(filename):
return[sum(i) for i in csvReader(filename)] #summing each pair of tuples
Plot('data.csv')
我期待着这样的东西:
[80,155,90,90,180]
我有一个类型错误:TypeError:不支持+的操作数类型:"int"one_answers"str">
def csvReader(filename): #Function for reading .csv file
with open(filename) as file:
reader = csv.reader(file, delimiter=' ')
next(reader, None)
data = [tuple(map(int, row)) for row in reader]
return(data)
csvReader('data.csv')
这应该能帮到你。首先,将"60"转换为60(str转换为int(,然后其他函数应该可以正常工作。
使用panda读取csv,并提取我们的需求。
a,b
10,20
15,5
30,40
import pandas as pd
df = pd.read_csv('data.csv', header=0)
df['sum'] = df['a'] + df['b']
tuple_requirement = tuple(zip(df['a'].to_list(), df['b'].to_list()))
sum_requirement = df['sum'].to_list()
print(sum_requirement)
print(tuple_requirement)
# [30, 20, 70]
# ((10, 20), (15, 5), (30, 40))
您可以评估整个文件行str
,而不是读取CSV然后将str
的序列转换为int
的序列。要安全地执行此操作,可以使用ast.literal_eval
:
>>> from ast import literal_eval
>>> literal_eval('1,2,3,4')
(1,2,3,4)
使用它:
with open(filename) as f:
next(f)
rows = [literal_eval(line) for line in f]
totals = [sum(row) for row in rows]