1

Python 的 splat 运算符的作用有几个答案(将列表或元组解包到被调用函数内的单独 args 中),但我找不到任何关于 splat 运算符如何将列表强制为元组的有趣副作用(有效地渲染传递一个列表splat 按值传递,而不是引用)。

那么,Python 的 splat 运算符是否将列表强制转换为元组:

def test(*arg):
    print(type(arg))
    for a in arg:
        print(a)

lst = ['roger', 'colleen']
print(type(lst))
test(*lst)         

tpl = ('roger', 'colleen')
print(type(tpl))
test(*tpl)

它似乎。上面的代码产生这个输出:

<class 'list'>
<class 'tuple'>
roger
colleen
<class 'tuple'>
<class 'tuple'>
roger
colleen

我正在努力巩固我对列表和元组的了解。我在这里读到

元组和列表之间的区别在于,元组不能更改,不像列表和元组使用括号,而列表使用方括号。

起初我很惊讶使用列表调用 test() 并没有让 test() 更改列表(它们不是不可变的)。但是当它们与 splat 运算符一起传递时,它们会起作用,因为它们被强制转换为元组。正确的?我认为!

更新: rkersh 的评论说得更清楚了:

test(*arg) 不是用列表调用的,而是用列表中的项目调用的 ——这些项目被 *arg 视为一个元组。

4

0 回答 0