【问题标题】:Not able to print the list, how to rectify the errors?无法打印列表,如何纠正错误?
【发布时间】:2017-09-14 05:36:12
【问题描述】:

这个程序是为了找到一个向量的归​​一化,但我无法打印列表:

定义函数:

def _unit_vector_sample_(vector):
    # calculate the magnitude
    x = vector[0]
    y = vector[1]
    z = vector[2]
    mag = ((x**2) + (y**2) + (z**2))**(1/2)
    # normalize the vector by dividing each component with the magnitude
    new_x = x/mag
    new_y = y/mag
    new_z = z/mag
    unit_vector = [new_x, new_y, new_z]
    #return unit_vector

主程序:

    vector=[2,3,-4]

    def _unit_vector_sample_(vector):
        print(unit_vector)

如何纠正错误?

【问题讨论】:

  • 将您的问题修复为实际问题并正确格式化您的代码以供显示。

标签: python-3.x list function


【解决方案1】:

试试这个:

def _unit_vector_sample_(vector):
    # calculate the magnitude
    x = vector[0]
    y = vector[1]
    z = vector[2]
    mag = ((x**2) + (y**2) + (z**2))**(1/2)
    # normalize the vector by dividing each component with the magnitude
    new_x = x/mag
    new_y = y/mag
    new_z = z/mag
    unit_vector = [new_x, new_y, new_z]
    return unit_vector

vector=[2,3,-4]  
print(_unit_vector_sample_(vector))

打印此输出:

[0.3713906763541037, 0.5570860145311556, -0.7427813527082074]

您需要在your _unit_vector_sample 函数中声明一个return 语句。否则,您的函数将运行,但无法将结果返回给 main。

您也可以这样做:

def _unit_vector_sample_(vector):
    # calculate the magnitude
    x = vector[0]
    y = vector[1]
    z = vector[2]
    mag = ((x**2) + (y**2) + (z**2))**(1/2)
    # normalize the vector by dividing each component with the magnitude
    new_x = x/mag
    new_y = y/mag
    new_z = z/mag
    unit_vector = [new_x, new_y, new_z]
    print(unit_vector)

vector=[2,3,-4]
_unit_vector_sample_(vector)

导致打印相同的输出:

[0.3713906763541037, 0.5570860145311556, -0.7427813527082074]

在这里,通过在函数中调用 print,每次运行函数时都会打印 unit_vector。

使用哪一个取决于您想要做什么。 您是否还想将函数的结果分配给 main 中的变量,然后使用第一个解决方案(而不是直接打印函数的结果,将其分配给变量)。如果不需要,您可以使用第二个选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    相关资源
    最近更新 更多