且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中将元组作为参数传递?

更新时间:2022-11-22 23:18:32

添加更多括号:

li.append((3, 'three'))

带有逗号的括号会创建一个元组,除非它是参数列表.

Parentheses with a comma create a tuple, unless it's a list of arguments.

这意味着:

()    # this is a 0-length tuple
(1,)  # this is a tuple containing "1"
1,    # this is a tuple containing "1"
(1)   # this is number one - it's exactly the same as:
1     # also number one
(1,2) # tuple with 2 elements
1,2   # tuple with 2 elements

长度为0的元组也会发生类似的情况:

A similar effect happens with 0-length tuple:

type() # <- missing argument
type(()) # returns <type 'tuple'>