python中tuple()函数的用法讲解,实例代码

python中的tuple()函数

tuple在python中指的是元组数据类型,tuple()函数是常用的内置函数之一,可以不接收参数,也可以接收一个python的可迭代的iterable对象参数,返回是一个tuple类型的值,相当于数据类型转换。其语法结构如下:

tuple()函数结构

tuple ( ) -> empty tuple; 或 tuple( iterable ) -> tuple initialized from iterable's items

python源码当中有一句话“If the argument is a tuple, the return value is the same object.”,意思大概就是如果传递的参数是tuple元组类型,则返回值是其本身。


tuple()函数参数

  • 无,返回一个空的元组;
  • iterable,可迭代对象(包括字符串),返回一个元组;

tuple()函数实例代码

>>> tuple() #无参数
()
>>> tuple((1,2,3)) #参数为元组,返回其本身
(1, 2, 3)
>>> tuple([5,6]) #参数为list列表
(5, 6)
>>> tuple({'a':1,'b':2}) #参数为dict字典,转换的是字典的key
('a', 'b')
>>> tuple({1,2,3}) #参数为set集合
(1, 2, 3)
>>> tuple(1) #参数为int,会提示TypeError,因为int不是iterable可迭代对象
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> tuple('abc') #参数为字符串
('a', 'b', 'c')
>>> tuple('')
()

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.