简体   繁体   English

将文件中的浮点数和字符串读入数据类型完整的元组列表中

[英]Read floats and strings from a file into a list of tuples with data types intact

Say I have a file example.txt and it looks like this:假设我有一个文件example.txt ,它看起来像这样:

12.592,92.219,Cat
42.643765,72.268234,Dog
12.24312121,22.24312121,Parrot
54.12311,91.32811,Monkey
...

How can I map both the first two float values and the string to a list of tuples?如何将前两个浮点值和字符串映射到元组列表? See below:见下文:

[('12.592','92.219','Cat'), ('42.643765','72.268234','Dog'), ('12.24312121','22.24312121','Parrot'), ('54.12311','91.32811','Monkey')]

Before I introduced String values to example.txt I was able to successfully read the floats in the file into a list of tuples using the following method:在我将字符串值引入example.txt之前,我能够使用以下方法成功地将文件中的浮点数读入元组列表中:

with open('data/example.txt') as f:
        dataset = [tuple(map(float, i.split(','))) for i in f]

Output: [('12.592','92.219'), ('42.643765','72.268234'), ('12.24312121','22.24312121'), ('54.12311','91.32811')]输出: [('12.592','92.219'), ('42.643765','72.268234'), ('12.24312121','22.24312121'), ('54.12311','91.32811')]

Use:用:

with open('data/example.txt') as f:
    # split each line by ","
    rows = [i.strip().split(",") for i in f]
    
    # transform only the first two chunks (numbers) and leave the last one as a string
    dataset = [(*map(float, numbers), string) for *numbers, string in rows]
    print(dataset)

Output输出

[(12.592, 92.219, 'Cat'), (42.643765, 72.268234, 'Dog'), (12.24312121, 22.24312121, 'Parrot'), (54.12311, 91.32811, 'Monkey')]

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

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