[英]How to split elements of .csv into two separate lists
So I am given a file with min and max values ordered as such:所以我得到了一个文件,其中的最小值和最大值是这样排序的:
12.0,-4.5
34.6,1.8
12.7,2.8
etc...
For the purposes of my program, I need to take each line and split it, putting one "column" of values in one list and the second "column" in another.就我的程序而言,我需要取每一行并将其拆分,将一个“列”值放在一个列表中,将第二个“列”放在另一个列表中。 This way I will be able to use all the first values for a calculation of average/min/max, and all the second values can be used for a separate calculation.
这样我将能够使用所有第一个值来计算平均值/最小值/最大值,并且所有第二个值都可以用于单独的计算。
So far, I have only been able to achieve splitting each line into separate elements, like this:到目前为止,我只能实现将每一行拆分为单独的元素,如下所示:
['12.0,-4.5'], ['34.6,1.8'], ['12.7,2.8'], etc...
But I want it to be:但我希望它是:
['12.0', '34.6', '12.7', etc...] and ['-4.5', '1.8', '2.8', etc...]
My code is as follows.我的代码如下。 I have tried to do sufficient commenting, but if you need further explanation (which I doubt) let me know!
我试图做足够的评论,但如果你需要进一步的解释(我怀疑)让我知道!
#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)
The main portion of the list confusion is the last four lines, how would I modify this to accompany my two list idea?列表混乱的主要部分是最后四行,我将如何修改它以配合我的两个列表想法?
Split each line, and append row[0]
to one list, row[1]
to the other list.拆分每一行,并将
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.