首先,您是否一定想做 OOP 而不是程序性的?您可以将大部分内容放在一个函数中并返回一个包含列表的元组(是的,这有点像 python 允许您从函数返回多个值的方式。)
OOP 版本就像@mike-vella 的答案。
在程序上,你可以写:
import csv
def get_datagroup(data):
# data is the filename = 'datafile.csv'
datafile = csv.reader(open(data,'rb'), delimiter=",", quotechar='|')
date, data1, data2, data3 = [], [], [], []
for row in datafile:
date.append(row[0])
data1.append(row[1])
data2.append(row[2])
data3.append(row[3])
return (date, data1, data2, data3)
datagroup1 = get_datagroup('datafile1.csv')
datagroup2 = get_datagroup('datafile2.csv')
问题:您想将每个连续文件的数据附加到相应的列表中吗?我猜是的,因为您使用过append
:
import csv
def get_datagroup(data, data_tuples):
# data is the filename = 'datafile.csv'
# data_tuples holds date, data1,2,3
datafile = csv.reader(open(data,'rb'), delimiter=",", quotechar='|')
# you can use: data_tuples[0], data_tuples[1], data_tuples[2], data_tuples[3]
# instead of : date, data1, data2, data3
date, data1, data2, data3 = data_tuples
for row in datafile:
date.append(row[0])
data1.append(row[1])
data2.append(row[2])
data3.append(row[3])
return (date, data1, data2, data3)
#initially, data tuples are empty
datagroup1 = get_datagroup('datafile1.csv', ([], [], [], []))
#then pass each subsequent call the last call's result tuple
#so that datagroup2 will have the results of datagroup1 and the new stuff
datagroup2 = get_datagroup('datafile2.csv', datagroup1)
您可以通过以下方式进行递归:
datagroup = ([], [], [], [])
datagroup = get_datagroup('datafile1.csv', datagroup)
datagroup = get_datagroup('datafile2.csv', datagroup)
datagroup = get_datagroup('datafile3.csv', datagroup)