python - python从文本文件到数组传输
问题描述
我有一个文本文件,如下所示:
[0.001,0.02,0.003]
[0.004,0.05,0.006]
我想制作一个这样的数组:
array([0.001,0.02,0.003],
[0.004,0.05,0.006]) etc.
所有元素都是浮动的。
我该怎么做?谢谢。
解决方案
这是一种方法
#First open the text file and turn each line into an element of a list.
with open("file.txt", 'r') as file_handle:
# convert file contents into a list
lines = file_handle.read().splitlines()
#Then convert the string into a list
for i in range(len(lines)):
#remove the "[" and "]" and split where there is a ","
lines[i] = lines[i].strip("[]").split(",")
for j in range(len(lines[i])):
#convert string to float
lines[i][j] = float(lines[i][j])
print(lines)
推荐阅读
- laravel - 带有 foreach 的 foreach 中的产品列表
- google-cloud-platform - 在项目中看不到共享机器映像
- unity3d - 如何相对于游戏对象本地位置向对象添加力
- unity3d - 部署到 Hololens 2
- javascript - 嵌入式 YouTube 问题(Java/脚本)
- python - 如何将 tkinter Entry() 值存储为浮点值?
- firebase - 使用 @react-native-firebase/auth 合并多个帐户
- c# - C# WPF 如何更改所有打开的窗口的窗口标题
- java - Spring boot 404 not found Error message": "No message available
- jquery - Select2 Remote Data 选择多个项目