【问题标题】:Value Error cannot index值错误无法索引
【发布时间】:2016-04-14 17:54:36
【问题描述】:
text_file = ['Cats','Dogs','Frogs','(pass)', 'ants']
final_l = [[1], [2], [3], [5]]
final_dict = {'Dogs': [1], 'Cats': [1], 'Frogs': [1], 'ants': [1]}

for k, v in final_dict.items():
    for sl in final_l:
        for num in sl:
            if text_file[int(num)] == k:
                sl.append(k)
                sl.append(v)
print(final_l)

Traceback (most recent call last):
  File "/Users/Luan/Desktop/1.py", line 9, in <module>
    if text_file[int(num)] == k:
ValueError: invalid literal for int() with base 10: 'Frogs'

好困惑。哪里出错了???为什么它一直给我这个值错误?为什么我不能索引? 我想这样说:

final_l = [[1, "Cats", [1]], [2, "Dogs", [1]], [3, "Frogs", [1]], [5, "ants", [1]]]

【问题讨论】:

  • 在修改 sl 的同时对其进行迭代,这听起来是一个很好的理由,类似于您发布的错误,您明白我的意思吗?

标签: python int literals base


【解决方案1】:

这里的主要问题是您在遍历列表的同时将新值附加到它会导致错误,并且因为您碰巧使用了附加到此列表sl 的值不适合索引(例如'Frogs'),所以我的明显建议是为此创建一个新列表:

>>> new = []
>>> for k,v in final_dict.items():
    for i,sl in enumerate(final_l):
        for num in sl:
            if text_file[num-1] == k:
                new.append(sl+[k,v])


>>> new
[[3, 'Frogs', [1]], [5, 'ants', [1]], [2, 'Dogs', [1]], [1, 'Cats', [1]]]

请注意,列表索引从 0 开始。

【讨论】:

  • 你是对的。谢谢!我认为这是最容易理解的方式
【解决方案2】:

导致错误是因为 text_file 是一个列表,您必须将一个整数传递给该列表的引用和索引。您正在传递 num ,它正在迭代一个在您对其进行操作时正在更改的列表。当您将“Frongs”和“[1]”附加到列表中时,num 会遍历这些值,然后您尝试引用 text_file 的索引“Frogs”。这会导致值错误。

你可以使用:

import copy
for num in copy.copy(sl):

作为一种可能的解决方案,尽管我对您的最终目标是什么感到很困惑。

【讨论】:

  • 抱歉.. 我正在尝试获取这样的列表:[[1, "Cats", [1]], [2, "Dogs", [1]], [3, “青蛙”,[1]],[5,“蚂蚁”,[1]]]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多