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 不能在函数中定义元组
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
