import numpy as np import matplotlib.pyplot as plt with open('01_nve_limit.lammpstrj', 'r') as f: data = f.readlines() #print(float(data[0])) for _ in range(9): #next(f) try: while True: a = next(f) print(a) except StopIteration: pass for line in f: #print(line) print(float(data[0])) data = np.loadtxt(f) print(data.reshape(-1,5)) b = np.logical_and(data[ : , 4 ] >= -35 ,data[ : , 4 ] <= 601) data = data[mask] data = data[np.argsort(data[:,4])] x = np.arange(-35, 600, 1) y = np.zeros_like(x) index = 0 for i in range(len(x)): while index < len(data) and data[index,4] < x[i]: index += 1 while index < len(data) and data[index,4] < x[i]+1: y[i] += data[index,5] index += 1 y[i] /= 879.4显示报错:b = np.logical_and(data[ : , 4 ] >= -35 ,data[ : , 4 ] <= 601) IndexError: too many indices怎么解决
时间: 2024-02-10 15:17:17 浏览: 26
这个错误是因为你使用了 `f` 迭代器两次,第一次迭代器已经迭代到了文件的末尾,所以第二次迭代时就没有数据了,导致你尝试访问不存在的数据而出现 `IndexError: too many indices` 错误。
你可以将 `data = np.loadtxt(f)` 这一行代码放在第一个 `for` 循环结束后,这样 `f` 迭代器就不会被耗尽,也不会出现上述错误。修改后的代码如下所示:
```
import numpy as np
import matplotlib.pyplot as plt
with open('01_nve_limit.lammpstrj', 'r') as f:
data = f.readlines()
#print(float(data[0]))
for _ in range(9):
#next(f)
try:
while True:
a = next(f)
print(a)
except StopIteration:
pass
# 将这行代码放在第一个 for 循环结束后
data = np.loadtxt(f)
print(data.reshape(-1,5))
b = np.logical_and(data[ : , 4 ] >= -35 ,data[ : , 4 ] <= 601)
data = data[mask]
data = data[np.argsort(data[:,4])]
x = np.arange(-35, 600, 1)
y = np.zeros_like(x)
index = 0
for i in range(len(x)):
while index < len(data) and data[index,4] < x[i]:
index += 1
while index < len(data) and data[index,4] < x[i]+1:
y[i] += data[index,5]
index += 1
y[i] /= 879.4
plt.plot(x, y)
plt.show()
```
如果你还有其他问题,请随时提出。