【问题标题】:List Comprehension Showing IndexError显示 IndexError 的列表理解
【发布时间】:2020-04-26 10:30:05
【问题描述】:

我正在创建一个刽子手游戏。我想出了一个用字母代替下划线的想法。首先,用户输入他们的猜测(在本例中为字母“c”)。我搜索一个包含未知单词字母的列表,创建一个列表,其中包含每次命中该字母时的索引。然后我搜索下划线列表并使用我创建的索引列表将所有下划线替换为字母。但是,我收到一个错误:

IndexError: 列表索引超出范围。

我在下面的代码中做错了什么?

y = "cctcc"
to_modify = ["_", "_", "_","_", "_"]
replacements = list(y)

user_input = input()
indexes = [i for i, j in enumerate(replacements) if j == user_input]
print(indexes)
for index in indexes:
  to_modify[indexes[index]] = replacements[index]

print(to_modify)

输出:

[0, 1, 3, 4]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-25-be2b07a156e5> in <module>()

     10 print(indexes)

     11 for index in indexes:

---> 12   to_modify[indexes[index]] = replacements[index]

     13 

     14 print(to_modify)


IndexError: list index out of range

【问题讨论】:

    标签: python list list-comprehension


    【解决方案1】:

    这部分代码已经循环遍历索引:

    for index in indexes:
        to_modify[indexes[index]] = replacements[index]
    

    如果indexes 包含[0,1,3,4],当index 循环到4 时,它试图访问超出范围的indexes[4],只需使用您从循环中获取的索引:

    for index in indexes:
        to_modify[index] = replacements[index]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多