将元组附加到列表 - 两种方式有什么区别?

Append a tuple to a list - what's the difference between two ways?

我在 4 个月前写了第一个 "Hello World"。从那以后,我一直在关注莱斯大学提供的 Coursera Python 课程。我最近参与了一个涉及元组和列表的小型项目。对我来说,将元组添加到列表中有些奇怪:

a_list = []
a_list.append((1, 2))       # Succeed! Tuple (1, 2) is appended to a_list
a_list.append(tuple(3, 4))  # Error message: ValueError: expecting Array or iterable

这让我很困惑。为什么使用 "tuple(...)" 而不是简单的“(...)”来指定要追加的元组会导致 ValueError?

顺便说一句:我用了 CodeSkulptor coding tool used in the course

应该没有区别,但是你的元组方法不对,试试:

a_list.append(tuple([3, 4]))

tuple 函数只有一个参数,必须是可迭代的

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items.

尝试使用 [3,4](列表)或 (3,4)(元组)

使 3,4 成为可迭代对象

例如

a_list.append(tuple((3, 4)))

会工作

append无关。 tuple(3, 4) 全部本身都会引发该错误。

原因是,正如错误消息所说,tuple 需要一个可迭代的参数。您可以通过将单个对象传递给元组来创建 单个 对象的 contents 的元组。你不能通过将它们作为单独的参数传递来创建两个事物的元组。

只需执行 (3, 4) 即可创建一个元组,就像您的第一个示例一样。没有理由不使用这种简单的语法来编写元组。

因为 tuple(3, 4) 不是创建元组的正确语法。正确的语法是 -

tuple([3, 4])

(3, 4)

你可以从这里看到它 - https://docs.python.org/2/library/functions.html#tuple

我相信 tuple() 接受一个列表作为参数 例如,

tuple([1,2,3]) # returns (1,2,3)

看看如果用方括号包裹数组会发生什么