【问题标题】:Trouble with zip when running for loop monte carlo sim; python运行 for loop monte carlo sim 时出现 zip 问题; Python
【发布时间】:2011-12-22 09:43:48
【问题描述】:

在 python 2.7 中工作。

我确信代码有点笨拙,但我会尽量简单地解释它。

我有两个列表:

T = [[1,0], [1,0], [0,5]]
S = [[1], [3], [2]]

我需要将B中对应的值添加到T中对应列表的末尾,所以使用zip,我把它们放在一起。

然后我计算每个列表的第一个值从第三个值中减去的结果,并使用另一个 zip 函数附加该值。

所以当我运行我的函数时,T 变量现在看起来像 [[1,0,1,0], [1,0,3,-2], [0,5,2,-2]]。

然后我有一系列 if 语句,如果某些值高于或低于其他值,则列表返回胜利、失败或平局。

我想多次模拟我的函数 (starterTrans) 的结果。问题是当我使用时:

def MonteCarlo(T, S, x):
    for i in range(0, x):
        starterTrans(T, S)

对于每次模拟,我都会得到不同版本的 T。所以第一次通过模拟时,T 在每个列表中都有适当数量的元素(四个),但在每次运行之后,添加的变量越来越多。

无论我想使用多少次,我都需要一种方法将 T 锁定到它原来的四个变量。我正在努力寻找一种方法来做到这一点。有什么想法吗?

我知道我的代码很复杂,但如果它可以帮助任何人按照我的尝试来描述我的问题:

def starterTrans(team, starter):
    wins = 0
    losses = 0
    nd = 0
    random.shuffle(team)
    for t, s in zip(team, starter):
        t.extend(s)
    score_add(team, exit_score(team, starter))
    length = len(starter)
    for i in range(0, length):
        if team[i][4] > 0 and (team[i][1] > -team[i][4]) and team[i][2] >= 5:
            wins += 1
        elif team[i][4] < 0 and (team[i][1] <= -team[i][4]):
            losses += 1
        elif (team[i][4] <= 0 and team[i][1] >= -team[i][4]):
            nd += 1
    return wins, losses, nd

def score_add(team, exit_scores):
    for t, e in zip(team, exit_scores):
        t.append(e)
    return team

def exit_score(team, starter):
    exit_scores = []
    length = len(starter)
    for i in range(0, length):
        score = team[i][0]-team[i][3]
        exit_scores.append(score)
    return exit_scores

def MonteCarlo(team, starter, x):
    for i in range(0, x):
        starterTrans(team, starter)

感谢您的帮助。

【问题讨论】:

  • 我想我可能已经修好了。
  • 如果我更改代码,那么 starterTrans 只需要一个参数(starter)
  • 然后我有 team = [[1,0], [1,0], [0,5]],team 始终保持不变。

标签: python for-loop zip montecarlo


【解决方案1】:

将最后一行更改为starterTrans(team[:], starter)。这将传递 team 的副本,而原件保持不变。

【讨论】:

  • 您是在说蒙特卡洛脚本?我试过了,它仍然添加到列表中。
【解决方案2】:

我认为你只需要改变这个:

def MonteCarlo(T, S, x):
    for i in range(0, x):
        starterTrans(T, S)

到这里:

def MonteCarlo(T, S, x):
    for i in range(0, x):
        starterTrans(T[:], S)

这会将T 的副本传递给starterTrans(..),而不是原始列表。如果您在starterTrans(..) 中编辑T 的元素,这将无济于事。在这里你需要一个深拷贝。在这里查看浅拷贝和深拷贝之间的区别:What is the difference between a deep copy and a shallow copy?。

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多