当元组中只有一个列表时,为什么元组的类型是一个列表?

2024-04-19 15:46:11 发布

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

x=([1,2,3])

类型(x)=列表

x=([1,2,3],[4,5,6])

类型(x)=元组

为什么类型会改变?你知道吗


Tags: 类型列表元组
1条回答
网友
1楼 · 发布于 2024-04-19 15:46:11

创建只有一个项的元组的正确语法是在该项后面加逗号:

x=([1,2,3],)

在这个例子中

type(x)=tuple

引用official Python 2 documentation

哪些州(引用)

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

相关问题 更多 >