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

Time:11-11

Say I have a file example.txt and it looks like this:

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:

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')]

CodePudding user response:

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')]
  • Related