Python can#39;t define tuples in a function(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 不能在函数中定义元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 不能在函数中定义元组


- 我如何卸载 PyTorch? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01