带字典和迭代的简单Python问题

2024-09-21 02:39:07 发布

您现在位置: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.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])

这是我的密码。“players”列表是策略对象的列表,其中“name”是字符串,“logic”是函数。我遇到的麻烦发生在线路上

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的字典里有键“Player 1 Name”,在玩家2的字典里有键“Player 2 Name”?你知道吗

编辑:更多的要求代码

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]]]

Tags: nameinforreturnifdefresulthistory
1条回答
网友
1楼 · 发布于 2024-09-21 02:39:07

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

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

if p.name != o.name and o.name not in p.history:

再说一遍,反复出现的囚徒困境的一部分是,战略应该与自身对抗,这样可能会更好:

if o.name not in p.history:

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

相关问题 更多 >

    热门问题