如何在Python中将元组作为参数传递? [英] How to pass tuple as argument in Python?
本文介绍了如何在Python中将元组作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想要一个元组列表.这是我的第一个主意:
Suppose I want a list of tuples. Here's my first idea:
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)
有效,但似乎过于冗长.有更好的方法吗?
which works, but seems overly verbose. Is there a better way?
推荐答案
添加更多括号:
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'>
这篇关于如何在Python中将元组作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文