Python can't define tuples in a function [duplicate]

戏子无情 提交于 2020-01-03 07:19:12

问题


For some reason in python everytime I try to define tuples in a function I get a syntax error. For example I have a function that adds vectors to the program, it looks like this:

def add_vectors((angle_1, l_1),(angle_2, l_2)):
    x=math.sin(angle1)*l_1+math.sin(angle2)*l_2
    y=math.cos(angle1)*l_1+math.cos(angle2)*l_2

    angle=0.5*math.pi-math.atan2(y, x)
    length=math.hypot(x, y)
    return (angle, length)

Which seems alright, but the interpretor says there is a syntax error and highlights the first bracket of the first tuple. I am using Python 3.2.3. What am I doing wrong?


回答1:


Tuple parameters are no longer support in Python3: http://www.python.org/dev/peps/pep-3113/

You may unpack your tuple at the beginning of your function:

def add_vectors(v1, v2):
    angle_1, l_1 = v1
    angle_2, l_2 = v2
    x=math.sin(angle1)*l_1+math.sin(angle2)*l_2
    y=math.cos(angle1)*l_1+math.cos(angle2)*l_2

    angle=0.5*math.pi-math.atan2(y, x)
    length=math.hypot(x, y)
    return (angle, length)



回答2:


There is no syntax for such tuple unpacking. Instead, take two tuples as arguments on their own and then unpack them into separate arguments.

def add_vectors(tup1, tup2):
    angle_1, l_1 = tup1
    angle_2, l_2 = tup2
    ...


来源:https://stackoverflow.com/questions/20035591/python-cant-define-tuples-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!