在列表中附加一个元组-这两种方法有什么区别?

2024-05-17 06:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

四个月前我写了我的第一篇“你好世界”。从那以后,我一直在学习莱斯大学提供的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

顺便说一下:我用了CodeSkulptorcoding tool used in the course


Tags: 项目列表is世界list大学课程元组
3条回答

^{}函数只接受一个必须是iterable的参数

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成为iterable

例如

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

会有用的

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

tuple([3, 4])

或者

(3, 4)

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

应该没有区别,但是您的元组方法是错误的,请尝试:

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

相关问题 更多 >