【问题标题】:How to pass tuple as argument in Python?如何在 Python 中将元组作为参数传递?
【发布时间】:2011-09-12 09:15:29
【问题描述】:

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

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)

这可行,但似乎过于冗长。有没有更好的办法?

【问题讨论】:

  • 希望以下链接能给您带来一些关于如何使用元组的知识:tutorialspoint.com/python/python_tuples.htm
  • @Artsiom Rudzenka - 该教程很危险 :( 它不仅有混合列表和元组之类的错误,而且出于某种原因,它还显示了一些愚蠢的事情,例如以 ; 结尾的行。
  • @viraptor 是的,你是对的,使用官方python教程总是更好:docs.python.org/tutorial/…
  • 早期版本的 Python 确实将 append(arg,...) 语法自动转换为 append((arg,...))。他们把它拿出来是因为它增加了混乱。旧书会显示您的示例有效。这就是为什么最好查看 Python.org 站点上的文档或您安装的 Python 发行版的原因。

标签: python list tuples


【解决方案1】:
def product(my_tuple):
    for i in my_tuple:
        print(i)

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

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

【讨论】:

  • 虽然这完全正确,但这是 OP 最初使用的内容,非常冗长。我建议详细说明这一点,并添加一些更多信息,以将其应用于 OP 的问题,并提供一个列表以改进您的答案
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    添加更多括号:

    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) 不是元组。在这种情况下,一对括号会被解析为其他语法含义(用于数学评估中的顺序和优先级?)。语法不同于[1],它是一个列表。
    【解决方案4】:

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

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

    【讨论】:

    【解决方案5】:

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

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 2017-08-10
      • 2022-01-02
      • 2011-10-05
      • 2012-05-24
      • 2016-11-18
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多