【问题标题】:Python 3: List inside dictionary, list index out of rangePython 3:字典内的列表,列表索引超出范围
【发布时间】:2013-06-28 23:51:31
【问题描述】:

我创建了一个字典,其中的条目是这样的列表:

new_dict
{0: ['p1', 'R', 'p2', 'S'], 1: ['p3', 'R', 'p4', 'P'], 2: ['p5', 'R', 'p6', 'S'], 3:   ['p7', 'R', 'p8', 'R'], 4: ['p9', 'P', 'p10', 'S'], 5: ['p11', 'R', 'p12', 'S'], 6: ['p13', 'S', 'p14', 'S']}  

从这里我试图检查列表中的元素是否在Moves 下方的列表中。比如在new_dict[0]中,我想检查Moves中的第一个元素和第三个元素,如果没有,则引发类异常。 (这是一个sn-p的代码。)

class NoStrategyError(Exception): pass

j=0
while j < len(new_dict):
    i = 0
    while i < 4:
        # Write the code for the NoSuchStratgyError 
        Moves = ['R', 'S', 'P', 'r', 's', 'p']
        if new_dict[j][1+4*i] not in Moves or new_dict[j][3+4*i] not in Moves:
            raise NoStrategyError("No such strategy exists!")
        i+=1
    j+=1

现在问题出在这里,当我运行它时,我收到以下错误:

if new_dict[j][1+4*i] not in Moves or new_dict[j][3+4*i] not in Moves: IndexError: list index out of range

这是什么意思?

有没有更好的方法来写内部while loop?并将其改为for loop?比如for elem in new_dict[j]

【问题讨论】:

  • 您的列表最多有 4 个元素,但 1 + 4 * i 从 1 变为 13。
  • 我才意识到。我不需要那个内在的while loop。呸!
  • 另外,你为什么使用带有连续整数键的字典而不是列表?
  • 键代表第 n 个游戏。但实际上,这也是因为我不得不将一个扁平的列表重新组合成四个人。如果不使用字典,我不知道该怎么做。
  • 可能会有所帮助:stackoverflow.com/questions/312443/…

标签: python list dictionary indexing


【解决方案1】:

请注意,在嵌套循环的第一次交互中,我们看到以下值都在 Moves 中:

>>>new_dict[0][1], new_dict[0][3] 
('R', 'S')

但是,在嵌套循环的第二次迭代中,您正在尝试评估字典中未包含的术语:

>>>new_dict[1][5], new_dict[1][7]
IndexError: list index out of range

注意 new_dict[1] 只有 4 个元素:

>>>new_dict[1]
['p3', 'R', 'p4', 'P']

所以只能引用new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3]:

>>>new_dict[1][0],new_dict[1][1],new_dict[1][2],new_dict[1][3]
('p3', 'R', 'p4', 'P')

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 2016-02-14
    • 2012-11-21
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多