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

时间:2011-06-10 10:00:18

标签: python list tuples

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

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)

哪个有效,但看起来过于冗长。还有更好的方法吗?

5 个答案:

答案 0 :(得分:41)

添加更多括号:

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'>

答案 1 :(得分:7)

这是因为不是一个元组,它是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')]

>>> 

答案 2 :(得分:3)

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

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()

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

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

baz((3, 1))

答案 3 :(得分:0)

它抛出该错误,因为list.append只接受一个参数

试试这个 list + = [&#39; x&#39;,&#39; y&#39;,&#39; z&#39;]

答案 4 :(得分:-1)

def product(my_tuple):
    for i in my_tuple:
        print(i)

my_tuple = (2,3,4,5)
product(my_tuple)

这是您将元组作为参数传递的方式