【问题标题】:list indices must be integers, not numpy.float64列表索引必须是整数,而不是 numpy.float64
【发布时间】:2020-04-13 15:46:28
【问题描述】:

当我尝试测试 .pkl 形式的数据集时,我遇到了这种错误。以下是出现此特定错误的代码部分:

f = open("TP_index_blstm.pkl",'wb')
    pickle.dump(result[1], f)
    f.close()
    #print(type(result[1]))
    f_TP = open("./result_analyze/BGRU/TP_filenames.txt","ab+")
    for i in range(len(str(result[1]))):
       TP_index = result[i]
       f_TP.write(str(filenames[TP_index])+'\n')

我不明白为什么会出现这个错误,我是这种错误的新手,请建议我解决这个 IndexError。 result[1] 的类型是 . 出现的错误如下:

Traceback (most recent call last):
  File "bgru.py", line 240, in <module>
    main(traindataSetPath, testdataSetPath, realtestdataSetPath, weightPath, resultPath, batchSize, maxLen, vectorDim, layers, dropout)
  File "bgru.py", line 154, in main
    f_TP.write((filenames[TP_index])+'\n')
TypeError: list indices must be integers, not numpy.float64

【问题讨论】:

  • " 结果[1] 的类型是 ." - 是什么?
  • 你可能想要"a",而不是"ab+",作为模式。如果您正在写入 str 值,并且您根本没有尝试从文件中读取,则不应以二进制模式打开它,因此不需要 +。
  • @chepner 当我从中删除 + 时,发生同样的错误......
  • 这不是问题的解决方案,只是一个不相关的建议。
  • @Błotosmętek 结果类型 [1] 是

标签: python


【解决方案1】:

在f_TP.write 行之前添加print(TP_index, type(TP_index)),您可能会找出问题所在。

TP_index根据错误是numpy.float64,所以不能作为数组索引使用。

【讨论】:

  • 是的,TP_index 的类型是 。那么我怎样才能消除这个错误呢?我试图为此找到解决方案,但我失败了
  • @angel filenames 是一个列表。列表由整数索引,即您可以调用filenames[i],其中i 是一个整数,这应该给出列表的ith 元素。在您的情况下,您正在调用filenames[TP_index],其中TP_index 不是整数,因此您有错误。想象一下TP_index = 1.234,列表的第 1.234 个元素没有意义,因此出现 TypeError。
  • 如果不知道您的输入文件是什么以及您想用它做什么,就很难提供更多帮助。
  • 我的输入文件是易受攻击的c或c++程序,现在我的输入文件是.pkl的形式,我正在尝试检查我的文件中是否存在漏洞,python目前我正在运行的程序是构建 bgru 模型,训练数据集并对其进行测试,并打印准确性等。
  • 抱歉,我不知道 .pkl 文件或 bgru 是什么。如果您可以提供Minimal, Reproducible Example 会更容易。
【解决方案2】:

“文件名”是一个列表,所以索引必须是整数。

my_list = ['a', 'e', 'i', 'o', 'u'] 
# index of my_list is 0, 1, 2, 3, 4
print('First element :', my_list[0])
output : 'a'

在你的情况下,我认为使用字典更好。

my_dict = {0.555:my_list}
print(my_dict[0.555])
output : ['a', 'e', 'i', 'o', 'u'] 

【讨论】:

    猜你喜欢
    • 2015-11-20
    • 2017-01-27
    • 2016-02-09
    • 2015-09-02
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多