简体   繁体   English

将带有字符串的列表转换为带浮点数的列表

[英]converting a list with strings into a list with floats

import csv
with open ('data.txt', 'r') as f:
    col_one = [row[0] for row in csv.reader(f, delimiter= '\t')]
    plots = col_one[1:]

The data in column one are floats, but above code makes list of strings. 第一列中的数据是浮点数,但上面的代码生成字符串列表。 How can I make the list of floats correcting above codes? 如何使浮动列表更正上述代码?

You can convert string to float using float() function 您可以使用float()函数将字符串转换为float

import csv
with open ('data.txt', 'r') as f:
    col_one = [float(row[0]) for index, row in enumerate(csv.reader(f, delimiter= '\t')) if index != 0]

Use the float built-in: 使用内置float

col = [float(row[0]) for row in rows]

http://docs.python.org/dev/library/functions.html#float http://docs.python.org/dev/library/functions.html#float

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

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