假设我想要一个元组列表。这是我的第一个想法:

li = []
li.append(3, 'three')

结果是:
Traceback (most recent call last):
  File "./foo.py", line 12, in <module>
    li.append('three', 3)
TypeError: append() takes exactly one argument (2 given)

因此,我求助于:
li = []
item = 3, 'three'
li.append(item)

可行,但似乎过于冗长。有没有更好的办法?

最佳答案

添加更多括号:

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

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

这意味着:
()    # 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长度元组也会发生类似的效果:
type() # <- missing argument
type(()) # returns <type 'tuple'>

10-08 13:33
查看更多