开发者

How can I convert a list type to a numeric type in Python

I have a external file that is a single column of floating point numbers ( want to be able to expand it to have multiple columns in the future). I want to import it into an array. The file is a cvs file but it just as well could be a txt file.

I am using:

reader = csv.reader(open("e=0.6.csv"))
table = []
for row in r开发者_开发知识库eader:
    values = []    
    for col in row: 
        values.append(float(col))
    table.aapend(values)

The result is a list [[1.0], [0.98], ......] I want to convert the List to an array of numbers (1.0, 0.98, ...) How can I do this?


reader = csv.reader(open("e=0.6.csv"))
table = tuple(float(col) for row in reader for col in row)


Why do you make a new list called values? Why not append to table instead? i.e.

reader = csv.reader(open("e=0.6.csv"))
table = []
for row in reader: 
    for col in row: 
        table.append(float(col))


(1.0, 0.98, ...) is a tuple. Here's one way to make a tuple from that:

>>> l = [[1.0], [0.98]]
>>> tuple(i[0] for i in l)
(1.0, 0.97999999999999998)


reader = csv.reader(open("e=0.6.csv"))
table = []
for row in reader:
    for col in row: 
        table.aapend(float(col))


Use a list comprehension:

>>> l = [[0.1], [0.2], [0.3]]
>>> [x[0] for x in l]
[0.1, 0.2, 0.3]

Or the map function:

>>> map(lambda x:x[0], l)
[0.1, 0.2, 0.3]

Or the reduce function:

>>> reduce(lambda x,y: x+y, l, [])
[0.1, 0.2, 0.3]

Or a generator:

>>> (x[0] for x in l)
<generator object <genexpr> at 0x1004e00f0>

Or just store your numbers directly in a list.


In your specific case, I'd skip this step and just do something like:

reader = csv.reader(open("e=0.6.csv"))

table = [float(col) for col in row for row in reader]

However if you wanted to go with your original answer you can do:

Use the map method:

>>> l = [[1.0], [0.98], [3.0]]
>>> map(lambda x: x[0], l)
[1.0, 0.97999999999999998, 3.0]

Or list comprehension:

>>> [e for subl in l for e in subl]
[1.0, 0.97999999999999998, 3.0]

In either case, you can convert the list returned into a tuple by just doing tuple(result)


I don't understand why you're using csv.reader in this case. You said yourself that it wasn't really a csv! Just do either:

map(float, open("e=0.6.csv").readlines())

or

[float(x) for x in open("e=0.6.csv").readlines()]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜