简体   繁体   English

如何将csv文件中的字符串转换为python中的列表

[英]how to turn string from csv file into list in python

I have a CSV file that contains matrix: 我有一个包含矩阵的CSV文件:

1,9,5,78
4.9,0,24,7
6,2,3,8
10,21.4,8,7

I want to create a function that returns list of lists: 我想创建一个返回列表列表的函数:

[[1.0,9.0,5.0,78.0],[4.9,0.0,24.0,7.0],[6.0,2.0,3.0,8.0],[10.0,21.4,8.0,7.0]]

this is my attempt: 这是我的尝试:

fileaname=".csv"
def get_csv_matrix(fileaname):
    mat=open(fileaname,'r')
    mat_list=[]
    for line in mat:
        line=line.strip()
        mat_line=[line]
        mat_list.append(mat_line)
return mat_list

but I get list of lists with one string: 但是我得到一个带有一个字符串的列表列表:

[['1,9,5,78'], ['4.9,0,24,7'], ['6,2,3,8'], ['10,21.4,8,7']]

how can i turn the lists of strings to lists of floats? 如何将字符串列表转换为浮点数列表?

mat_line = [line]

This line just takes the line as a single string and makes it into a one element list. 该行仅将其作为单个字符串并使其成为一个元素列表。 If you want to separate it by commas, instead do: 如果要用逗号分隔,请执行以下操作:

mat_line = line.split(',')

If you want to also turn them into numbers, you'll have to do: 如果还要将它们转换为数字,则必须执行以下操作:

mat_line = [float(i) for i in line.split(',')]

I find it easier to read a list comprehension than a for loop. 我发现阅读列表理解要比for循环更容易。

def get_csv_matrix(filename):
    with open(filename) as input_file:
        return [[float(i) for i in line.split(',')] for line in input_file]

print (get_csv_matrix("data.csv"))

The above function opens a file (I use with to avoid leaking open file descriptors), iterates over the lines, splits each line, and converts each item into a floating-point number. 上述功能打开文件(I使用with以避免泄漏打开文件描述符),在所述线迭代,将每个线,并且每个项转换为浮点数。

Try 尝试

fileaname=".csv"
def get_csv_matrix(fileaname):
    mat=open(fileaname,'r')
    mat_list=[]
    for line in mat:
        line=line.strip()
        mat_line=line.split(",")
        for i in mat_line:
            i_position = line.index(i)
            line[i_position] = float(i)
        mat_list.append(mat_line)
    return mat_list

If any object in mat_line isn't an integer, you will come up with an error, so I suggest you create a validation method to be absolutely sure that it is an integer. 如果mat_line中的任何对象都不是整数,则会出现错误,因此建议您创建一个验证方法以绝对确保它是整数。

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

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