简体   繁体   English

如何将csv中的每一列保存到列表中?

[英]How can I save each column in a csv into a list?

I'm trying to make each column into a list the following way: 我正在尝试通过以下方式使每一列进入列表:

f = open('file.csv', 'r') 
a = [float(item.split('.')[0]) for item in f]
b = [float(item.split('.')[1]) for item in f]

When I print a I get a list with all the values of the first column, but when I print b it shows an empty list. 当我打印a我得到一个包含第一列所有值的列表,但是当我打印b它显示了一个空列表。 I tried changing the columns of a with that of b and a gives me the column I'm asking for, just after the first defined list it keeps showing empty lists. 我尝试将a的列更改为b并将a的列更改为我要的列,就在第一个定义的列表之后,它一直显示空列表。

You can also just use a csv.reader : 您也可以只使用csv.reader

import csv

list_a = []
list_b = []

with open('file.csv', newline='') as csv_file:
    reader = csv.reader(csv_file, delimiter='.')
    next(reader, None)  # Skip the header.
    for a, b in reader:
        list_a.append(float(a))
        list_b.append(float(b))

Or with the zip trick: 或使用zip技巧:

with open('file.csv', newline='') as csv_file:
    reader = csv.reader(csv_file, delimiter='.')
    next(reader, None)  # Skip the header.
    list_a, list_b = zip(*(map(float, row) for row in reader))

a = [float(item.split('.')[0]) for item in f] reads everything from the file. a = [float(item.split('.')[0]) for item in f]从文件中读取所有内容。 There is nothing left for the second list comprehension. 第二个列表理解没有什么可剩下的了。 You must close the file and open it again, eg: 您必须关闭文件然后再次打开它,例如:

with open('file.csv', 'r') as f:
    a = [float(item.split('.')[0]) for item in f] 
with open('file.csv', 'r') as f:
    b = [float(item.split('.')[1]) for item in f]

But it is even better to read the file only once and process both a's and b's in one loop: 但是,最好只读取一次文件并在一个循环中处理a和b都更好:

with open('file.csv', 'r') as f:
    a, b = zip(*[map(float, item.split('.')) for item in f])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM