Python Tuple(元组) tuple()方法
描述
Python 元组 tuple() 函数将列表转换为元组。
语法
tuple()方法语法:
tuple( iterable )
参数
- iterable -- 要转换为元组的可迭代序列。
返回值
返回元组。
实例
以下实例展示了 tuple()函数的使用方法:
实例 1
>>>tuple([1,2,3,4])
(1, 2, 3, 4)
>>> tuple({1:2,3:4}) #针对字典 会返回字典的key组成的tuple
(1, 3)
>>> tuple((1,2,3,4)) #元组会返回元组自身
(1, 2, 3, 4)
实例 2
#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc'];
aTuple = tuple(aList)
print "Tuple elements : ", aTuple
以上实例输出结果为:
Tuple elements : (123, 'xyz', 'zara', 'abc')
Python 元组
Gene Lowe
276***5132@qq.com
tuple() 函数不是改变值的类型,而是返回改变类型后的值,原值不会被改变:
test_list1 = ('a','b','c') test_list2 = ['x','y','z'] test_tuple = tuple(test_list2) # test_list2 可以修改,tuple() 函数不是改变值的类型,而是返回改变类型后的值,原值不会被改变 test_list2[2] = '这是修改的' #下面这行报错,元组不可修改 # test_list1[2]='这是修改的' print(test_list1) print(test_list2) print(test_tuple)Gene Lowe
276***5132@qq.com