1

我刚刚学会了解包,*所以进行了一些测试。我意识到虽然有些人写过将元组作为参数作为位置参数传递,但我也可以传递字符串、列表和集合,只要我包含*. 我在下面列出了我定义为接受位置参数和测试用例的函数。

让我感到惊讶的是Tracebacks,这导致了我的问题。即使没有提供元组,s 也提到了一个元组TracebackIndexError当使用 时,引擎盖下发生的事情是列表、字符串和集合转换成元组*吗?

>>> def print2nd(*args):
...     print(args[1])

>>> s = "abc"
>>> print2nd(*s)
b
>>> print2nd(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in print2nd
IndexError: tuple index out of range

>>> t = ['a', 'b', 'c']
>>> print2nd(*t)
b
>>> u = set(['a', 'b', 'c'])
>>> print2nd(*u)
a
>>> print2nd(u)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in print2nd
IndexError: tuple index out of range
>>> u[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
>>> tuple(u)
('b', 'a', 'c')
>>> tuple(u)[1]
'a'
4

0 回答 0