简体   繁体   English

从字符串列表到浮点列表

[英]from list of strings into list of floats

I have a text file (data.txt) delimited by tab as follows: 我有一个用制表符分隔的文本文件(data.txt),如下所示:

name    height  weight
A   15.5    55.7
B   18.9    51.6
C   17.4    67.3
D   11.4    34.5
E   23.4    92.1

The program below gives the result as the list of strings. 下面的程序将结果作为字符串列表给出。

with open('data.txt', 'r') as f:
    col1 = [line.split()[0] for line in f]
    data1 = col1 [1:]
    print (data1)
with open('data.txt', 'r') as f:
    col2 = [line.split()[1] for line in f]
    data2 = col2 [1:]
    print (data2)
with open('data.txt', 'r') as f: 
    col3 = [line.split()[2] for line in f]
    data3 = col3 [1:]
    print (data3)

The results are as follows: 结果如下:

['A', 'B', 'C', 'D', 'E']
['15.5', '18.9', '17.4', '11.4', '23.4']
['55.7', '51.6', '67.3', '34.5', '92.1']

But, I want to get data2 and data3 as the list of floats. 但是,我想获取data2和data3作为浮动列表。 How can I correct above program? 我该如何纠正以上程序? Any help, please. 请帮忙。

There is no need of reading the file 3 times here, you can do this by defining a simple function that returns float value of the the item if it is a valid number otherwise returns it as it is. 此处无需读取文件3次,您可以通过定义一个简单函数来实现此目的,如果该函数是有效数字,则该函数将返回该项目的浮点值,否则将按原样返回。

Now read all the lines one by one using a list comprehension and apply this function to the items of each line. 现在,使用列表理解一一读取所有行,并将此功能应用于每一行的项目。 So now you've a list of lists, and it's time to unzip that list of lists using zip(*) and assign the return value to data1 , data2 , data3 因此,现在您有了一个列表列表,是时候使用zip(*)解压缩列表列表并将返回值分配给data1data2data3

def ret_float(x):
    try:
        return float(x)
    except ValueError:
        return x

with open('data.txt') as f:
    next(f) #skip the header
    lis = [ map(ret_float,line.split()) for line in f]
    #[['A', 15.5, 55.7], ['B', 18.9, 51.6], ['C', 17.4, 67.3], ['D', 11.4, 34.5], ['E', 23.4, 92.1]]
    #unzip the list
    data1, data2, data3 = zip(*lis)

    #if you want data1,data2,data3 to be lists then use:
    #data1, data2, data3 = [list(x) for x in  zip(*lis)]
...     
>>> data1
('A', 'B', 'C', 'D', 'E')
>>> data2
(15.5, 18.9, 17.4, 11.4, 23.4)
>>> data3
(55.7, 51.6, 67.3, 34.5, 92.1)

Update : Fixing your solution 更新 :解决您的问题

with open('data.txt', 'r') as f:
    col2 = [line.split()[1] for line in f]
    data2 = list(map(float, col2 [1:]))   # apply float to each item using `map`
                                          # as `map` returns a `map` object in py3.x
                                          # you have to pass it to list() 
with open('data.txt', 'r') as f: 
    col3 = [line.split()[2] for line in f]
    data3 = list(map(float, col3 [1:]))
    print (data3)

help on map : map 帮助

>>> print(map.__doc__)
map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables.  Stops when the shortest iterable is exhausted.

Use the float() function. 使用float()函数。 It takes 1 arg, which would be the string/var you want to turn into a float. 它需要1个arg,它将是您想要转换为浮点型的字符串/ var。

Use the float() command: 使用float()命令:

with open('data.txt', 'r') as f:
    col2 = [float(line.split()[1]) for line in f]
    data2 = col2[1:]
    print(data2)

Convert the strings to float as you read them: 读取时将字符串转换为float

data1 = col1 [1:]

becomes 变成

data1 = float(col1 [1:])

But--and I know you didn't ask this--your approach is a little sideways. 但是-我知道您没有问这个-您的方法有点偏斜。 You might want to consider a program structure more like this: 您可能想考虑一个更像这样的程序结构:

data0 = []
data1 = []
data2 = []
with open('data.txt', 'r') as f:
    f.readline()
    for line in f:
        vals = line.split()
        data0.append(vals[0])
        data1.append(vals[1])
        data2.append(vals[2])
print(data0)
print(data1)
print(data2)

Hope it helps! 希望能帮助到你!

(Disclaimer: works with Python 2.7; not sure about 3.x.) (免责声明:适用于Python 2.7;不确定3.x。)

with open('data.txt', 'r') as f:
    col1 = [line.split()[0] for line in f]
    data1 = col1 [1:]
    print (data1)
with open('data.txt', 'r') as f:
    col2 = [line.split()[1] for line in f]
    data2 = float(col2 [1:])
    print (data2)
with open('data.txt', 'r') as f: 
    col3 = [line.split()[2] for line in f]
    data3 = float(col3 [1:])
    print (data3)

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

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