j_2112_ari
j_2112_ari

Reputation: 33

Type cast certain values in a nested list

I have a nested list of strings:

station_data = [['65.29', 3003', 'station1'], ['81.23', '8000', 'station2'], ['77.33', '3500', 'station3']] etc...

I am trying to type cast the first position [0] of each list from string to float

I am trying to type cast the second position [1] of each sub list from string to int

I have tried different for loops, but for the life of me I cannot seem to get the syntax right

station_data can be modified, or a new list can be created, fine either way.

Desired output should look like: station_data_processed = [[65.29, 3003, 'station1'], [81.23, 8000, 'station2'], [77.33, 3500, 'station3']]

Any suggestions are a huge help, thank you!

Upvotes: 2

Views: 274

Answers (2)

Buddy Bob
Buddy Bob

Reputation: 5889

You can make use of try/except's

station_data = [['65.29', '3003', 'station1'], ['81.23', '8000', 'station2'], ['77.33', '3500', 'station3']]
l = []
for lst in station_data:
    group = []
    for val in lst:
        try:
            val = int(val)
        except ValueError:
            try:
                val = float(val)
            except ValueError:
                pass
        group.append(val)
    l.append(group)

output

[[65.29, 3003, 'station1'], [81.23, 8000, 'station2'], [77.33, 3500, 'station3']]

Upvotes: -1

btonasse
btonasse

Reputation: 102

You can do a list comprehension:

converted_list = [[float(i[0]), int(i[1]), i[2]] for i in station_data]

Upvotes: 2

Related Questions