Python 不能在函数中定义元组 [英] Python can't define tuples in a function

查看:60
本文介绍了Python 不能在函数中定义元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,在 python 中,每次我尝试在函数中定义元组时都会出现语法错误.例如我有一个向程序添加向量的函数,它看起来像这样:

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)

这似乎没问题,但解释器说存在语法错误并突出显示第一个元组的第一个括号.我正在使用 Python 3.2.3.我做错了什么?

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?

推荐答案

Python3 不再支持元组参数:http://www.python.org/dev/peps/pep-3113/

Tuple parameters are no longer supported 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)

这篇关于Python 不能在函数中定义元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆