python 数据结构--Tuple(元组)
生活随笔
收集整理的這篇文章主要介紹了
python 数据结构--Tuple(元组)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 Tuple(元組)
Python的元組與列表類似,不同之處在于元組的元素不能修改(前面多次提到的字符串也是不能修改的)。創建元組的方法很簡單:如果你使用逗號分隔了一些值,就會自動創建元組。
1.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')
1.2 元組的基本操作
1.2.1 訪問元組
mix = (123,456,'hello','apple')
mix[1]
456
mix[0:3]
(123, 456, 'hello')
1.2.2 修改元組
元組中的元素值不允許修改,但可以對元組進行連接組合。
a = (123,456)
b = ('abc','def')
a+b
(123, 456, 'abc', 'def')
1.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
1.2.4 元組索引、截取
因為元組也是一個序列,所以可以訪問元組中指定位置的元素,也可以截取索引中的一段元素
string = ('number','string', 'list', 'tuple','dictionary')
string[2]
'list'
string[-2]
'tuple'
string[2:-2]
('list',)
1.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)
1.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] 是一個列表,修改時,是修改的列表中的值,這個列表還是原來的列表,及元組中的值不變,變化的是列表中到的元素。
1.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)
總結
以上是生活随笔為你收集整理的python 数据结构--Tuple(元组)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件需求分析—消息管理
- 下一篇: 必备idea 插件plugins 提高