gpt4 book ai didi

python - numpy 数组列出转换问题

转载 作者:太空狗 更新时间:2023-10-30 00:29:57 25 4
gpt4 key购买 nike

出于某种原因,evalRow(list(array([0, 1, 0, 0, 0])))evalRow([0, 1, 0, 0, 0 ]) 给出不同的结果。但是,如果我使用 magicConvert(此处用于调试)而不是 list 从 numpy 数组到列表,它会按预期工作:

def magicConvert(a):
ss = str(list(a))[1:-1]
return map(int, ss.split(","))

# You don't actually need to read these functions, just here to reproduce the error:
from itertools import *
def evalRow(r):
grouped = map(
lambda (v, l): (v, len(tuple(l))),
groupby(chain([2], r, [2])))
result = 0
for player in (1, -1):
for (pre, mid, post) in allTuples(grouped, 3):
if mid[0] == player:
result += player * streakScore(mid[1], (pre[0] == 0) + (post[0] == 0))
return result

def streakScore(size, blanks):
return 0 if blanks == 0 else (
100 ** (size - 1) * (1 if blanks == 1 else 10))

def allTuples(l, size):
return map(lambda i: l[i : i + size], xrange(len(l) - size + 1))

最佳答案

行为的差异是由于执行 list(some_array) 返回 numpy.int64 列表,同时通过字符串表示进行转换(或等效地使用 tolist() 方法)返回 python 的 int 列表:

In [21]: import numpy as np

In [22]: ar = np.array([1,2,3])

In [23]: list(ar)
Out[23]: [1, 2, 3]

In [24]: type(list(ar)[0])
Out[24]: numpy.int64

In [25]: type(ar.tolist()[0])
Out[25]: builtins.int

我认为罪魁祸首是您代码中的 100 ** (size - 1) 部分:

In [26]: 100 ** (np.int64(50) - 1)
Out[26]: 0

In [27]: 100 ** (50 - 1)
Out[27]: 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

In [28]: type(100 ** (np.int64(50) - 1))
Out[28]: numpy.int64

您看到的是 int64 溢出,因此求幂的结果本质上是“随机的”,而 python 的 int 具有无限范围并给出正确的结果。

总结:

  • 如果您想在 numpy 和 python 数据类型之间进行转换,请使用适当的方法,在本例中为 array.tolist()
  • 请记住,numpy 的数据类型具有有限的范围,因此应该检查溢出并在其他情况下预料到奇怪的结果。如果您没有使用正确的转换方法,您最终可能会在意想不到的情况下使用 numpy 数据类型(如本例)。
  • 永远不要假设它是 python/numpy/一个使用非常广泛的库中的错误。在如此经过良好测试和广泛使用的软件中,在如此微不足道的情况下发现错误的机会非常小。如果程序给出了意想不到的结果,99.999% 的情况是因为做错了什么。因此,在责备他人之前,请尝试逐步检查您的程序在做什么。

关于python - numpy 数组列出转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19791223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com