我正尝试访问字典中列表中的索引项目。字典有两个键,第一个是一个ID键,然后每个ID都有一个关联的字典,其中的日期时间对象作为键。列表索引超出范围。不过,我可以打印我想要使用的列表索引
我正在过滤字典,因为我之前在代码中做了很多次,并且出现了一个特殊的“列表索引超出范围”错误。我知道python从0开始索引,并考虑到了这一点。
我想访问列表中的第五个元素,当我得到这个错误。但是,如果我将python调试器插入到我的代码中,则可以打印出产生错误的相同索引元素。
An image of the command prompt when I try to run the code
def plot_histogram(dict, newpath):
norm_res = []
res = [] # should I also plot a histogram of the residual?
for id in dict:
for dt in dict[id]:
import pdb; pdb.set_trace()
if dict[id][dt][5] is not None: # np.nan
norm_res.append(float(dict[id][dt][5])) # Need to exclud None results. But want to exclude them for both
# norm res and res at the same time so that neither result is skewed
res.append(float(dict[id][dt][4])) # unfailry. (?)
f = plt.figure()
sns.distplot(norm_res)
f.savefig(newpath + r'\sns_norm_res_histogram.png', dpi=500)
g = plt.figure()
sns.distplot(res)
g.savefig(newpath + r'\sns_res_histogram.png', dpi=500)
return
我认为错误可能是与事实,我想访问的最后一个元素列表,而有时这种元素是无类的事情。这是否意味着当无元素处于最后位置时,列表的长度会缩短?
非常感谢您的帮助。
那么,没有'dict [id] [dt] [5])',你必须检查产生你的字典的代码。请注意,对于变量名,'dict'是一个不错的选择,因为它是一个Python内置函数。 –
它为什么让我打印字典[id] [dt] [5](请参阅后链接的照片)? @ThierryLathuille –
如果您想包含提示,您应该将其编辑到问题中。我们通常不会下载外部内容。 –