字典和迭代的简单Python问题

字典和迭代的简单Python问题,python,Python,我正在用Python编写一个迭代囚徒困境的实现,我遇到了以下问题 for p in players: for o in players: if p.name != o.name: try: p.history[o.name] except KeyError: p.history[o.name] = [] o.history[p.n

我正在用Python编写一个迭代囚徒困境的实现,我遇到了以下问题

for p in players:
    for o in players:
        if p.name != o.name:
            try:
                p.history[o.name]
            except KeyError:
                p.history[o.name] = []
                o.history[p.name] = []
                for i in xrange(0,2):
                    result = play(p.logic(p.history[o.name]),
                                  o.logic(o.history[p.name]))
                    p.history[o.name].append(result[0])
                    o.history[p.name].append(result[1])
这是我的密码。“玩家”列表是策略对象的列表,其中“名称”是字符串,“逻辑”是函数。我遇到的麻烦发生在生产线上

p.history[o.name].append(result[0])
我正在尝试创建以下词典:

Player 1.history = {"Player 2 Name": [result, result, result]}
Player 2.history = {"Player 1 Name": [result, result, result]}
但我得到的却是:

Player 1.history = {"Player 1 Name": [wrong results], 
                    "Player 2 Name": [wrong results]}
结果并不全是错的,但有些是错的。有人知道为什么结果不正确,或者为什么我在玩家1的字典中有键“玩家1名称”,在玩家2的字典中有键“玩家2名称”吗

编辑:根据要求添加更多代码

class Strategy:
    """Basic class for all strategies to use. The 'logic' function is defined oustide and governs behavior"""
    def __init__(self, logic, name):
        self.logic = logic
        self.name = name
    history = {}

def makePlayer(name):
    if name == "Defects":
        def logic(hist):
            return 1
    if name == "Tit for Tat":
        def logic(hist):
            for i in xrange(1,3):
                try:
                    if hist[len(hist) -  i][1] == 1:
                        return 1
                except IndexError:
                    pass
            return 0
    return Strategy(logic, name)

payoff = [[100, 0], [101, 1]]

def play(choice1, choice2): #choiceFoo = 0 => cooperate; 1 => defect
    return [[choice1, choice2, payoff[choice1][choice2]], [choice2, choice1, payoff[choice2][choice1]]]

这不是一个完整的答案,但在异常块中执行“实际工作”必然会引起混乱。如果要查看字典中是否有键,请使用操作中的
显式执行此操作

通过将条件更改为,可以删除try/except块

if p.name != o.name and o.name not in p.history:
再者,反复出现的囚徒困境的一部分是,战略应该与自身对抗,这样可能更好:

if o.name not in p.history:

如果没有更多麻烦的代码(例如,
play
),就很难对这个问题给出更多的建议。

我不确定问题到底是什么,但我认为这似乎与迭代或字典没有任何特别的关系,只是您的逻辑中存在一些问题。好的,我理解您关于异常与条件的观点,并使用后一个if语句编辑了我的代码。我还编辑了原始帖子,加入了有关“播放”功能的详细信息,尽管我认为它们不重要。