所以给了我一个文件,其最小值和最大值按如下顺序排列:
12.0,-4.5
34.6,1.8
12.7,2.8
etc...
就我的程序而言,我需要将每一行分开,将一个值的“列”放在一个列表中,将第二个“列”放在另一个列表中。这样,我将可以使用所有第一个值进行平均值/最小值/最大值的计算,而所有第二个值都可以用于单独的计算。
到目前为止,我只能实现将每一行拆分为单独的元素,如下所示:
['12.0,-4.5'], ['34.6,1.8'], ['12.7,2.8'], etc...
但是我希望它是:
['12.0', '34.6', '12.7', etc...] and ['-4.5', '1.8', '2.8', etc...]
我的代码如下。我已尝试做足够的评论,但是如果您需要进一步的解释(我怀疑),请告诉我!
#import libraries to be used
import time
fileChoice = input("Enter the file name: ")
inputFile = open(fileChoice)
catTypes = inputFile.readline().strip('\n').split(',') #the headers of the file, taking away special characters
numOfHeadings = len(catTypes) #determining how many headers there are
print(catTypes) #printing the headers for future reference
rowCount = sum(1 for row in inputFile) #counting rows for later use
inputFile.close()
li = open(fileChoice) #opening file again for data collection
li.readline()
li = [entry.split() for entry in li] #creating list for every line in .csv file
print(li)
列表混乱的主要部分是最后四行,我该如何修改以配合我的两个列表想法?
答案 0 :(得分:1)
分割每一行,并将row[0]
附加到一个列表,row[1]
附加到另一列表。
import csv
mins = []
maxs = []
with open(fileChoice) as f:
f.readline() # Skip header line
csvin = csv.reader(f)
for row in csvin:
maxs.append(row[0])
mins.append(row[1])