str(list [index]):IndexError:列表索引超出范围

时间:2019-04-05 21:15:25

标签: python list numpy

我只是试图加载文件,提取其第一和第三列,将它们随机化,并生成一个新文件,如下所示:

DocumentFile documentFile = DocumentFile.fromFile(file);
documentFile.delete();

AFAIK,DocumentsContract.deleteDocument(context.getContentResolver(), Uri.fromFile(file ); import random import numpy as np q0 = np.loadtxt("G:\\out.txt")[:, 0].tolist() q2 = np.loadtxt("G:\\out.txt")[:, 2].tolist() z0 = [round(random.uniform(-4,4),4) for x in range(488)] z2 = [round(random.uniform(-4,4),4) for x in range(488)] r_pos_coord = [round(sum(x),3) for x in zip(q0,z0)] r_tar_coord = [round(sum(x),3) for x in zip(q2,z2)] t_pos_coord = [round(random.uniform(0,360),4) for x in range(488)] t_tar_coord = [round(random.uniform(0,360),4) for x in range(488)] par1 = [random.randint(0,1) for x in range(488)] par2 = [x-1 if x==1 else x+1 for x in par1] p = [1 for x in range(488)] with open('G:\\target.txt', 'w') as writer: for index in range(1,488): writer.write(str(r_pos_coord[index])) writer.write(' \t') writer.write(str(t_pos_coord[index])) writer.write(' \t') writer.write(str(r_tar_coord[index])) writer.write(' \t') writer.write(str(t_tar_coord[index])) writer.write(' \t') writer.write(str(par1[index])) writer.write('\t') writer.write(str(par2[index])) writer.write('\t') writer.write(str(p[index])) writer.write('\n') 均已列出。因此,我应该能够通过它们的索引访问它们的条目。但是,Python会引发以下错误:

r_pos_coord

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

q0的{​​{1}}少于len。当您488时,zip的len小于488。在某些时候,循环中存在索引错误。您可能希望固定长度,以免发生这种不可预测的行为

看看MCVE

r_pos_coord

产量

a = [1, 2, 3, 4]
b = [10,20,30]

list(zip(a,b))

现在,假设您希望基于两个数组中最长的[(1,10), (2, 20), (3, 30)] 进行压缩。为此itertools has a nice function

len

收益

import itertools as it
list(it.zip_longest(a,b))

对于固定的[(1, 10), (2, 20), (3, 30), (4, None)] 长度列表并压缩了可变IO 488文件,out.txt可能是解决方法。