【发布时间】: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 个游戏。但实际上,这也是因为我不得不将一个扁平的列表重新组合成四个人。如果不使用字典,我不知道该怎么做。
标签: python list dictionary indexing