首页 > 解决方案 > 当我尝试重塑时,它给我一个错误说“TypeError:列表索引必须是整数或切片,而不是元组”

问题描述

实际上,我正在尝试将 Matlab 代码转换为 python,当我尝试重塑时,它会抛出一个 TypeError 说“TypeError:列表索引必须是整数或切片,而不是元组”。

MATLAB

[file,path] = uigetfile('*.dwr');
fid = fopen(strcat(path,'/',file));
m5 = (fread(fid, '*uint8'));
m5=double(m5);
fclose(fid);
m6=m5(12514:end);
no_bin_ele=m5(12039:2:12218)+256*m5(12040:2:12218);
s1=size(m6);
s2=((no_bin_ele(1)*7+4)*360)*1;
n1=m6(1:s2);
j1=reshape(n1(1:end,1),no_bin_ele(1)*7+4,360*1);

Python

import numpy as np
with open('aa.dwr', 'rb') as fp:
m5 = np.fromstring(fp.read(), dtype='uint8')
m5 = m5.astype(float)
m5 = m5.tolist()
m6 = m5[12514:]
no_bin_ele = m5[12039:12218:2]+256*m5[12040:12218:2]
s1 = len(m6)
s2=((no_bin_ele[1]*7+4)*360)*1
s2 =int(s2)
n1=m6[1:s2]
j1 = np.reshape(n1[1: ,1], no_bin_ele[1]*7+4, 360*1)

错误

回溯(最后一次调用):文件“ppp.py”,第 26 行,在 j1 = np.reshape(n1[1: ,1], no_bin_ele[1]*7+4, 360*1) 类型错误:列出索引必须是整数或切片,而不是元组

标签: pythonmatlabnumpyreshape

解决方案


请尝试将第二个和第三个参数括在括号中,将其压缩为 1:

j1 = np.reshape(n1[1: ,1], (no_bin_ele[1]*7+4, 360*1))

如此处所示:https ://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html 我希望它有所帮助。


推荐阅读