我今天开始学习python并发现这个非常好的代码可视化工具pythontutor.com,问题是我仍然没有完全获得示例代码的一些语法.
def listSum(numbers):
if not numbers:
return 0
else:
(f, rest) = numbers
return f + listSum(rest)
myList = (1, (2, (3, None)))
total = listSum(myList)
什么(f,休息)=数字是什么意思?
解决方法:
这是元组拆包.
以这种方式使用时,元组中需要有2个项目.或多或少会导致异常,如下所示.
>>> numbers = (1, 2, 3, 4, 5)
>>> (f, rest) = numbers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> numbers = (1, 2)
>>> (f, rest) = numbers
>>> print f
1
>>> print rest
2
>>> numbers = (1)
>>> (f, rest) = numbers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> numbers = (1,)
>>> (f, rest) = numbers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
注意,(1)和(1,)在语法上是不同的,只有后者是一个元组.
有关详细信息,请参阅Tuples and Sequences上的Python Doc.