【问题标题】:Removed element from list but range has changed?从列表中删除元素但范围已更改?
【发布时间】:2014-04-08 07:54:32
【问题描述】:

我刚刚学会了如何从list 中删除某些内容。

rando = keywords[random.randint(0, 14)]
h = 0
for h in range(len(keywords)):
    if rando == keywords[h]:
        position = h

realAns = definitions[position]
del keywords [h]

但是,当我使用while 循环时,部分代码会不断重复,并且当我通过删除元素更改范围时,会出现回溯错误,指出它超出范围。我该如何解决? 谢谢:)

【问题讨论】:

标签: python python-3.x coding-style


【解决方案1】:

代码看起来不错,可能是您没有定义列表中包含 14 个条目的列表“关键字”。

当您尝试访问未定义的列表部分时,您会收到“列表超出范围”错误。 例如看下面的代码

list_of_rollnumbers = [11,24,31,57,42,99,132]
print list_of_rollnumbers[7]
print list_of_rollnumbers[9] #both these would give list index out of range error
print list_of_rollnumbers[5] #this would print 99

【讨论】:

    【解决方案2】:

    你为什么还要做那个循环?据我了解,您在随机索引处选择项目,然后查看整个列表以找到该项目,以便找到它的索引。做吧:

    position = random.randrange(len(keywords))
    rando = keywords[position]
    realAns = definitions[position]
    

    或者,更简单:

    rando, realAns = random.choice(list(zip(keywords, definitions)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2012-06-03
      • 2017-08-22
      • 1970-01-01
      • 2018-09-05
      相关资源
      最近更新 更多