如何在Python中将列表类型转换为数字类型
我有一个外部文件,它是一列浮点数(希望将来能够将其扩展为多列)。我想将其导入到数组中。该文件是 cvs 文件,但也可以是 txt 文件。
我正在使用:
reader = csv.reader(open("e=0.6.csv"))
table = []
for row in reader:
values = []
for col in row:
values.append(float(col))
table.aapend(values)
结果是一个列表 [[1.0], [0.98], ......]
我想将列表转换为数字数组 (1.0, 0.98, ...)
我该怎么做?
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 reader:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
为什么要创建一个名为值的新列表?为什么不附加到表中呢? IE
Why do you make a new list called values? Why not append to table instead? i.e.
(1.0, 0.98, ...)
是一个元组。这是从中创建元组的一种方法:(1.0, 0.98, ...)
is a tuple. Here's one way to make a tuple from that:使用列表理解:
或者映射函数:
或者化简函数:
或者生成器:
或者直接将数字存储在列表中。
Use a list comprehension:
Or the map function:
Or the reduce function:
Or a generator:
Or just store your numbers directly in a list.
在你的具体情况下,我会跳过这一步,只做类似的事情:
但是,如果你想使用原来的答案,你可以这样做:
使用 映射方法:
或列表理解:
无论哪种情况,您都可以通过执行
tuple(result)
将返回的列表转换为元组In your specific case, I'd skip this step and just do something like:
However if you wanted to go with your original answer you can do:
Use the map method:
Or list comprehension:
In either case, you can convert the list returned into a tuple by just doing
tuple(result)
我不明白您为什么在这种情况下使用
csv.reader
。你自己说过这不是真正的 csv!只需执行以下任一操作:或
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:or