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

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

假设我有一个文件 example.txt,它看起来像这样:

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

如何将前两个浮点值和字符串映射到元组列表?见下文:

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

在我将字符串值引入 example.txt 之前,我能够使用以下方法成功地将文件中的浮点数读取到元组列表中:

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

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

使用:

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)

输出

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