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

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

问题描述

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

  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。我在做什么错了?

解决方案

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



你可以在你的函数开头解开你的元组:

  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)
返回(角度,长度)


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?

解决方案

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)

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

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