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

Eri*_*son 20 python tuples list

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

li = []
li.append(3, 'three')
Run Code Online (Sandbox Code Playgroud)

结果如下:

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

所以我求助于:

li = []
item = 3, 'three'
li.append(item)
Run Code Online (Sandbox Code Playgroud)

哪个有效,但看起来过于冗长.有没有更好的办法?

vir*_*tor 43

添加更多括号:

li.append((3, 'three'))
Run Code Online (Sandbox Code Playgroud)

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

这意味着:

()    # 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
Run Code Online (Sandbox Code Playgroud)

0长度元组也会发生类似的效果:

type() # <- missing argument
type(()) # returns <type 'tuple'>
Run Code Online (Sandbox Code Playgroud)

  • 值得明确指出`(1)不是元组。在这种情况下,一对括号会被解析为其他语法含义(用于数学评估中的顺序和优先级?)。语法与列表中的[1]不同。 (3认同)

pax*_*blo 8

这是因为这不是一个元组,它是该add方法的两个参数.如果你想给它一个参数是一个元组,那么参数本身必须是(3, 'three'):

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> li = []

>>> li.append(3, 'three')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 given)

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

>>> li
[(3, 'three')]

>>> 
Run Code Online (Sandbox Code Playgroud)


Sim*_*got 5

在返回和赋值语句中,用于定义元组的括号是可选的。即:

foo = 3, 1
# equivalent to
foo = (3, 1)

def bar():
    return 3, 1
# equivalent to
def bar():
    return (3, 1)

first, second = bar()
# equivalent to
(first, second) = bar()
Run Code Online (Sandbox Code Playgroud)

在函数调用中,必须显式定义元组:

def baz(myTuple):
    first, second = myTuple
    return first

baz((3, 1))
Run Code Online (Sandbox Code Playgroud)

  • 这对我有帮助。我还发现您可以更早地打开包装,例如`def baz((first,second)):` (2认同)