创新互联Python教程:Pythontuple()
内置函数tuple()有助于在 python 中创建元组。元组是具有多个元素的单个变量。元组中的元素是不可变的,这意味着不能修改它。

创新互联专注于眉山网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供眉山营销型网站建设,眉山网站制作、眉山网页设计、眉山网站官网定制、小程序定制开发服务,打造眉山网络公司原创品牌,更为您提供眉山网站排名全网营销落地服务。
**tuple(iterable)** #where iterable may be list, range, dict etc
元组()参数:
接受单个参数。元组元素是有序的,不可更改的,并且允许重复的值。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 可迭代的 | 可列举的(列表、范围等)。)或迭代器对象 | 可选择的 |
元组()返回值
如果 iterable 没有传递给tuple(),该函数将创建一个空的 tuple 并返回一个 TypeError。
| 投入 | 返回值 | | 如果可迭代 | 元组 |
Python 中tuple()方法的示例
示例 1:如何使用tuple()创建元组
tuple1 = tuple()
print('tuple1 =', tuple1)
# creating a tuple from a list
tuple2 = tuple([2, 3, 5])
print('tuple2 =', tuple2)
# creating a tuple from a string
tuple1 = tuple('Python')
print('tuple1 =',tuple1)
# creating a tuple from a dictionary
tuple1 = tuple({2: 'one', 4: 'two'})
print('tuple1 =',tuple1)
输出:
tuple1 = ()
tuple2 = (2, 3, 5)
tuple1 = ('P', 'y', 't', 'h', 'o', 'n')
tuple1 = (2, 4)示例 2:用元组()演示类型错误的程序
# Error when a non-iterable is passed
tuple1 = tuple(1)
print(tuple1)
输出:
Traceback (most recent call last):
File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in
tuple1=tuple(1)
TypeError: 'int' object is not iterable 分享标题:创新互联Python教程:Pythontuple()
标题路径:http://www.jxjierui.cn/article/dphheje.html


咨询
建站咨询
