开发者

Looping Through Nested List - Convert from String to Float

开发者 https://www.devze.com 2023-04-11 11:26 出处:网络
I am new to Python, so apologies if this seems extremely simple: I have a csv file with 4 columns and a dozen rows. I import the contests as a list (list of lists), and the contents come in as string

I am new to Python, so apologies if this seems extremely simple:

I have a csv file with 4 columns and a dozen rows. I import the contests as a list (list of lists), and the contents come in as strings. What I want to do is loop through the list (wh开发者_C百科ich can be a variable number of rows) and convert the index 2 string to a float. I run the following code, but when i print the list, everything is still a string:

import csv

def main():
    benchmark = list(csv.reader(open('test.csv', 'r')))

    for i in range((len(benchmark))):
        benchmark[i][2] = float(benchmark[i][2])

Any help would be much appreciated.

Thanks!


It's not necessary to cast your csv.reader to a list as it is already iterable. You can do something like the following:

benchmark=[]
with open('test.csv','r') as inp:
    csvin=csv.reader(inp)
    for row in csvin:
        benchmark.append(row[:1] + [float(row[1])] + row[2:])


This would probably work, but I can't test without test data.

>>> benchmark = [[1, 2, 3, 4], [5, 6, 7, 8]]
>>> [[float(col) if i == 2 else col for i, col in enumerate(row)] for row in benchmark]
[[1, 2, 3.0, 4], [5, 6, 7.0, 8]]
0

精彩评论

暂无评论...
验证码 换一张
取 消