python 数据类型--Tuple(元组)


Python 3中有5种标准的对象类型:

  • Number(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Dictionary(字典)

4 Tuple(元组)

Python的元组与列表类似,不同之处在于元组的元素不能修改(前面多次提到的字符串也是不能修改的)。创建元组的方法很简单:如果你使用逗号分隔了一些值,就会自动创建元组。

4.1 创建元组

1,2,3
(1, 2, 3)
('hello', 'world')
('hello', 'world')
() #  空元组
()
(1,) #  逗号不能少
(1,)
tuple('hello,world')  # tuple 函数创建元组
('h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd')
# tuple('hello','world')
#---------------------------------------------------------------------------
#TypeError                                 Traceback (most recent call last)
#<ipython-input-13-b3c1d433db80> in <module>()
#----> 1 tuple('hello','world')
#
#TypeError: tuple() takes at most 1 argument (2 given)
tuple(['hello', 'world'])
('hello', 'world')

4.2 元组的基本操作

4.2.1 访问元组

mix = (123,456,'hello','apple')
mix[1]
456
mix[0:3]
(123, 456, 'hello')

4.2.2 修改元组

元组中的元素值不允许修改,但可以对元组进行连接组合。

a = (123,456)
b = ('abc','def')
a+b
(123, 456, 'abc', 'def')

4.2.3 删除元组

元组中的元素值不允许删除,但可以使用del语句删除整个元组。

num = (1,2,3,4,5,6)
# del num[1]    #TypeError: 'tuple' object doesn't support item deletion
del num
# num          # NameError: name 'num' is not defined

4.2.4 元组索引、截取

因为元组也是一个序列,所以可以访问元组中指定位置的元素,也可以截取索引中的一段元素

string = ('number','string', 'list', 'tuple','dictionary')
string[2]
'list'
string[-2]
'tuple'
string[2:-2]
('list',)

4.2.5 元组内置函数

Python元组提供了一些内置函数,如计算元素个数、返回最大值、返回最小值、列表转换等函数。

tup = (1,2,3,4,5,6,7,8,9,10)

len(tup)
10
max(tup)
10
min(tup)
1
num = [1,2,3,4,5]
tup = tuple(num)
tup
(1, 2, 3, 4, 5)

4.3 元组和列表的区别

因为元组不可变,所以代码更安全。如果可能,能用元组代替列表就尽量用元组。列表与元组的区别在于元组的元素不能修改,元组一旦初始化就不能修改。

t = ('a','b',['A','B'])
t
('a', 'b', ['A', 'B'])
t[2]
['A', 'B']
t[2][0]
'A'
t[2][1]
'B'
t[2][0] = 'X'  
t[2][1] = 'Y'
t[2]
['X', 'Y']

元组的第三个元素为t[2],t[2] 是一个列表,修改时,是修改的列表中的值,这个列表还是原来的列表,及元组中的值不变,变化的是列表中到的元素。

4.4 元组和列的相互转化

tup =  (1,2,[3,4],(5,6))
tup
(1, 2, [3, 4], (5, 6))
list(tup)
[1, 2, [3, 4], (5, 6)]
list(tup[3])
[5, 6]
tuple(list(tup))
(1, 2, [3, 4], (5, 6))
tuple(tup[2])
(3, 4)
发布了15 篇原创文章 · 获赞 0 · 访问量 231

猜你喜欢

转载自blog.csdn.net/qq_38249388/article/details/104871391