python中的append命令

2024-09-29 21:46:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,我认为是正确的。但是,它应该返回一个值的向量,但是它返回一个单独的累积值。在

pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1

def move(p, U):
    q = []
    for i in range(len(p)):
        s = pExact * p[(i - U) % len(p)]
        s = s + pOvershoot * p[(i - U - 1) % len(p)]
        s = s + pUndershoot * p[(i - U + 1) % len(p)]

        print i, s  # check if calculations are corrects
    q.append(s)

    return q        # should return a vector

p = [0, 1, 0, 0]
print move(p, 1)    # prints only cumulated value

我试图理解为什么它只打印一个值[0.10000000000000001]而不是一个向量[0, 0.1, 0.8, 0.1]我认为应该这样。在


Tags: 代码informovelenreturnifdef
3条回答

只是压痕问题。您的行q.append(s)与函数的主要部分处于相同的缩进级别,这意味着它只在for循环结束后执行。将它向右移动一级,这样它就可以与循环体的其余部分一起执行,并且每次都会在循环中执行。在

q.append(s)中的标识错误。它应该在for循环内。在

以下是正确版本:

pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1

def move(p, U):
    q = []
    for i in range(len(p)):
        s = pExact * p[(i - U) % len(p)]
        s = s + pOvershoot * p[(i - U - 1) % len(p)]
        s = s + pUndershoot * p[(i - U + 1) % len(p)]

        print i, s  # check if calculations are corrects
        q.append(s)

    return q        # should return a vector

p = [0, 1, 0, 0]
print move(p, 1)    # prints only cumulated value

不要使用q,而是使用更多的Python产量

def move(p, U):
    for i in range(len(p)):
        s = pExact * p[(i - U) % len(p)]
        s = s + pOvershoot * p[(i - U - 1) % len(p)]
        s = s + pUndershoot * p[(i - U + 1) % len(p)]

        print i, s  # check if calculations are corrects
        yield s

另外,代码的问题是您忘记了q.append(s)之前的4个空格缩进

相关问题 更多 >

    热门问题