Python不能在函数中定义元组 [英] Python can't define tuples in a function
本文介绍了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屋!
查看全文