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

21

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

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)

这样做可以工作,但似乎有些啰嗦。有更好的方法吗?


希望以下链接能为您提供一些关于如何使用元组的指导:http://www.tutorialspoint.com/python/python_tuples.htm - Artsiom Rudzenka
1
@Artsiom Rudzenka - 那个教程很危险 :( 它不仅有像混合列表和元组这样的错误,而且还展示了一些愚蠢的事情,比如出于某种原因以 ; 结尾的行。 - viraptor
3
@viraptor 没错,你说得对,最好使用官方的 Python 教程:http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences - Artsiom Rudzenka
1
早期版本的Python会自动将append(arg,...)语法转换为append((arg,...))。但是他们将其删除是因为它增加了混淆。旧书籍会展示你的例子可以工作。这就是为什么最好检查Python.org网站或已安装的Python发行版上的文档。 - yam655
5个回答

49

增加更多括号:

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

3
值得明确指出的是,(1) 并不是元组。在这种情况下,一对括号被解析为其他语法含义(用于数学计算中的顺序和优先级?)。这种语法与 [1] 不同,后者表示一个列表。 - neurite

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

>>> 

6

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

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

2
这对我很有帮助。我还发现你可以提前解包,例如 def baz((first, second)): - djeikyb
只有当你卡在Python 2中时才需要查看https://dev59.com/EWIj5IYBdhLWcg3wpmoH。 - Dave

0

它会抛出该错误是因为list.append仅接受一个参数

尝试这个 list += ['x', 'y', 'z']


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

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

这是如何将元组作为参数传递的


虽然这是完全正确的,但这是OP最初使用的,非常冗长。我建议详细说明并添加一些关于如何将其应用于OP问题的信息列表,以改进您的答案。 - user1781290

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接