Python 将数据读入二维数组?
我正在尝试将数据文件读入二维数组。 例如:Python 将数据读入二维数组?,python,arrays,Python,Arrays,我正在尝试将数据文件读入二维数组。 例如: file.dat: 123a 4 5 6 b 7 8 9 c 我试过这样的方法: file=open("file.dat","r") var = [[]] var.append([j for j in i.split()] for i in file) 但那没用 我需要二维数组形式的数据,因为之后我需要对每个元素进行操作,例如 for k in range(3): newval(k) = var[k,1] 你知道怎么做吗?file=op
file.dat
:
123a
4 5 6 b
7 8 9 c
我试过这样的方法:
file=open("file.dat","r")
var = [[]]
var.append([j for j in i.split()] for i in file)
但那没用
我需要二维数组形式的数据,因为之后我需要对每个元素进行操作,例如
for k in range(3):
newval(k) = var[k,1]
你知道怎么做吗?file=open(“file.dat”,“r”)#打开文件阅读
file = open("file.dat", "r") # open file for reading
var = [] # initialize empty array
for line in file:
var.append(line.strip().split(' ')) # split each line on the <space>, and turn it into an array
# thus creating an array of arrays.
file.close() # close file.
var=[]#初始化空数组
对于文件中的行:
var.append(line.strip().split(“”))#将
#从而创建一个数组数组。
file.close()#关闭文件。
这对我很有用:
with open("/path/to/file", 'r') as f:
lines = [[float(n) for n in line.strip().split(' ')] for line in f]
人们在评论中说,这真的很奇怪,没有一条线可以解决这个问题。我只花了很少的测试就成功了 Python中确实没有多维数组构造。最接近的是一个包含对其他列表的引用的列表。嗨@savanto,我试过了,但是当我试图打印第2行和第3行的第三个元素(print(var[1:2][2])时,我得到了一个错误:print(var[1:2][2])indexer:list index超出了range@user3578925不能像Python中那样跨行访问“矩阵”
var[1:3]
返回一个维度为2x4的数组,然后使用[2]
访问索引2会产生越界错误,因为只有索引0和1。试试这个:print([var[i][2]代表范围(1,3)])
谢谢@savanto!成功了!我开始认为Python不是进行繁重数学计算的最佳选择!
v = []
with open("data.txt", 'r') as file:
for line in file:
if line.split():
line = [float(x) for x in line.split()]
v.append(line)
print(v)