How to pass tuple as argument in Python?

独自空忆成欢 提交于 2020-05-24 21:14:11

问题


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?


回答1:


Add more parentheses:

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

Parentheses with a comma create a tuple, unless it's a list of 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:

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



回答2:


It's because that's not a tuple, it's two arguments to the add method. If you want to give it one argument which is a tuple, the argument itself has to be (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')]

>>> 



回答3:


Parentheses used to define a tuple are optional in return and assignement statements. i.e:

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:

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

baz((3, 1))



回答4:


it throws that error because list.append only takes one argument

try this list += ['x','y','z']




回答5:


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



来源:https://stackoverflow.com/questions/6304808/how-to-pass-tuple-as-argument-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!