简体   繁体   English

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

[英]How to pass tuple as argument in Python?

Suppose I want a list of tuples.假设我想要一个元组列表。 Here's my first idea:这是我的第一个想法:

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

Which results in:结果是:

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

So I resort to:所以我求助于:

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

which works, but seems overly verbose.这有效,但似乎过于冗长。 Is there a better way?有没有更好的办法?

Add more parentheses:添加更多括号:

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

Parentheses with a comma create a tuple, unless it's a list of arguments.带逗号的括号创建一个元组,除非它是 arguments 的列表。

That means:这意味着:

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

A similar effect happens with 0-length tuple:长度为 0 的元组也会产生类似的效果:

type() # <- missing argument
type(()) # returns <type 'tuple'>

It's because that's not a tuple, it's two arguments to the add method.这是因为那不是一个元组,它是两个 arguments 到add方法。 If you want to give it one argument which is a tuple, the argument itself has to be (3, 'three') :如果你想给它一个元组参数,参数本身必须是(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')]

>>> 

Parentheses used to define a tuple are optional in return and assignement statements.用于定义元组的括号在 return 和 assignment 语句中是可选的。 ie: IE:

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

in function call, you have to explicitely define the tuple:在 function 调用中,您必须明确定义元组:

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

baz((3, 1))

it throws that error because list.append only takes one argument它会抛出该错误,因为 list.append 只需要一个参数

try this list += ['x','y','z']试试这个列表 += ['x','y','z']

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

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

This how you pass Tuple as an argument这就是您将元组作为参数传递的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM