迭代简单列表时的ValueError

时间:2018-01-11 19:02:01

标签: python python-3.x

我正在尝试(作为一个新的Pythoneer)将旧的家庭作业从Java翻译成Python。当我尝试遍历列表时,我得到一个TypeError。它声称我没有使用整数值作为我的索引,但我看不出我不是。我可能包含了太多的代码,但以防错误不在我认为的位置( TypeError在最后一行):

def power(x, y):
    if isinstance(y, int):
        solution = x
        if y == 0:
            return 1
        else:
            for i in range(1,y):
                solution = solution*x
        return solution
    else:
        raise TypeError("Power: Non-Integer power argument")

def factorial(x):
    if isinstance(x, int) and x >= 0:
        if x == 1 or x == 0:
            return 1
        else:
            solution = int(x)
            while x > 1:
                solution = solution*(x-1)
                x -= 1
            return solution
    else:
        raise TypeError("Factorial: argument must be a positive integer")

def abs(x):
    if x < 0:
        x = -x
    return x


# Calculates the coefficients of the
# Taylor series of Sin(x).
# center argument must be 0, pi/4, pi, or 3pi/2
def coef_calc(center):
    coef = [1]*32
    i = int(0)
    c_temp = 1  # temporary holding place for calculated coefficient

    if center in [0, PI/4, PI, 3*PI/2]:

        # Mclauren Series (center = 0)
        if center == 0:
            while c_temp > 1.0e-31:
                c_temp = power(-1, i)/factorial(2*i + 1)
                coef[i] = c_temp
                i += 1
    else:
        raise ValueError("Argument not in [0, pi/4, pi, 3pi/2]")

    return coef


# CONSTANTS
PI = 3.1415926535897932
SQRT_TWO = 1.41421356237309504880

if __name__ == "__main__":
    print(power(4,2))
    print(factorial(4))
    print(abs(-0))

    coef = coef_calc(0)
    for x in coef:
        print(coef[x] + "\n")

2 个答案:

答案 0 :(得分:4)

当您执行for x in coef:时,x是遍历coef而不是其索引的项目,因此当您执行coef[x]时,期望x成为coef索引for i, x in enumerate(coef):,导致错误。如果您想同时获取索引和项目,请使用i,其中x是索引,print(x) 是项目。

您的代码很容易修复。只需将最后一行改为:

q

您不需要“\ n”,因为每个print语句都是一个新行。

答案 1 :(得分:0)

  • 我运行代码变量coef中有浮点值
  • 我会做的是下列内容:

    for i in range(len(coef)):
        print(coef[i],"\n")
    
  • 这种方式是按索引访问列表而不是按值访问

  • 如果您想按值访问它:

    for i in range(len(coef)):
        print(i,"\n")