tuple是Python中另外最基本的數據結構。序列中的每個元素都分配一個索引index - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推。
tuple與list有著相同的數據結構, 區別在於tuple是靜態的數據類型,list是動態的數據類型。
tuple對象創建(1)語法糖()創建
代碼示例
print("-- 利用 () 創建 tuple ")
print("字符串tuple:", ('a', 'b', 'c', 'd', 'e', 'f', 'g'))
print("數字tuple:",( (1, 2, 3), (11, 22, 33, 444), (-1, -2)))
print("空tuple:", ())-- 利用 () 創建 tuple
字符串tuple: ('a', 'b', 'c', 'd', 'e', 'f', 'g')
數字tuple: ((1, 2, 3), (11, 22, 33, 444), (-1, -2))
空tuple: ()(2)通過class tuple實例化創建
class tuple(object):
"""
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple.
If iterable is specified the tuple is initialized from iterable's items.
If the argument is a tuple, the return value is the same object.
"""
def __init__(self, seq=()): # known special case of tuple.__init__
"""
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple.
If iterable is specified the tuple is initialized from iterable's items.
If the argument is a tuple, the return value is the same object.
# (copied from class doc)
"""
pass
The argument must be an iterable if specified,其構造過程就是將可迭代對象遍歷,然後將遍歷所得元素依次塞入 list中,因此: 傳入 字符串 --> 每個字符組成的tuple 傳入 list --> list變tuple 傳入 tuple --> 原先的tuple 傳入 dict -->dcit 的 key 組成的tupleprint("-- 利用 class tuple 實例化 創建 tuple ")
print("傳入 空 生成tuple:", tuple())
print("傳入 'abcdefg' 生成tuple:", tuple('abcdefg'))
print("傳入 (11,22,33,123) 生成tuple:", tuple((11, 22, 33, 123)))
print("傳入 {'name': 'xiaole', 'height' :170 } 生成列表:",
tuple({'name': 'xiaole', 'height': 170}))-- 利用 class tuple 實例化 創建 tuple
傳入 空 生成tuple: ()
傳入 'abcdefg' 生成tuple: ('a', 'b', 'c', 'd', 'e', 'f', 'g')
傳入 (11,22,33,123) 生成tuple: (11, 22, 33, 123)
傳入 {'name': 'xiaole', 'height' :170 } 生成列表: ('name', 'height')
tuple 常用操作符 元組的常用操作符描述[]對元組進行索引訪問[:]對元組進行切片操作+對元組進行相加*對元組進行重複輸出>,==等關係運算符,對元組進行關係運算in判斷元素是否在元組中[] tuple索引查詢/元素訪問基本語法
element = tuple_demo[index]功能
tuple也是一種線性的序列結構,可以通過index來訪問tuple中的元素,[]中給定索引值index即可訪問tuple中的元素。
Python 中的索引分為正索引和負索引。 正索引從 0 開始進行編號, 表示數據集合中的第一個元素。 負索引從-1 開始編號, 表示tuple中倒數第一個元素。
正負索引值必須在有效的範圍之內, 否則會拋出越界訪問的錯誤信息。
越界訪問的錯誤信息 ---> IndexError: list index out of range
示例、利用[]訪問list數據容器的元素、修改元素值
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
numbers = (1, 2, 3, 4)
# 1.讀取列表中的第一個元素
first_number = numbers[0]
print('當前tuple為:', numbers, ", 其中第一個元素為:", first_number)
# 2.讀取列表中的最後一個元素
last_number = numbers[-1]
print('當前tuple為:', numbers, ", 其中最後一個元素為:", last_number)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
當前tuple為: (1, 2, 3, 4) , 其中第一個元素為: 1
當前tuple為: (1, 2, 3, 4) , 其中最後一個元素為: 4
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[:] tuple切片new_list = tuple_demo[:]功能:對數據容器tuple進行切片
注意事項:切片為淺拷貝(shallow copy),修改切片數據對原數據有影響
示例
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# 定義tuple類型變量
numbers = (1, 2, 3, 4)
# 切片操作
print("切片 numbers[0:2]為:", numbers[0:2]) # 第 0~1 號元素
print("切片 numbers[2:]為:", ) # 第 2~end 號元素
print("切片 numbers[-3:-1]為:", ) # 2~end-1 第 號元素
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
切片 numbers[0:2]為: (1, 2)
切片 numbers[2:]為:
切片 numbers[-3:-1]為:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ tuple合併基本語法
new_tuple = tuple0 + tuple1功能:tuple的加法是把兩個tuple中的元素合併,並返回一個新tuple。
代碼示例、
print("---")
# 定義變量 negative_numbers 表示負數
negative_numbers = (-1, -2, -3, -4)
# 定義變量 positive_numbers 表示正數
positive_numbers = (1, 2, 3, 4)
# tuple合併
print("合併後的tuple", negative_numbers + positive_numbers)
print("原負數tuple", negative_numbers)
print("原整數tuple", positive_numbers)
print("---")---
合併後的tuple (-1, -2, -3, -4, 1, 2, 3, 4)
原負數tuple (-1, -2, -3, -4)
原整數tuple (1, 2, 3, 4)
---
* tuple賦值擴展基本語法:
new_tuple = tuple1 * number功能:對tuple進行複製擴展, 返回一個新的tuple。
代碼示例:tuple三倍擴展
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# tuple 定義與三倍擴展
numbers = (-1,-2,-3)
print("擴展後的tuple",numbers * 3)
print("原tuple",numbers )
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
擴展後的tuple (-1, -2, -3, -1, -2, -3, -1, -2, -3)
原tuple (-1, -2, -3)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
== tuple元素相等判斷基本語法
boolean_var = tuple0 == tuple1功能、按序比較,從tuple的第1個元素開始, 逐元素進行比較tuple元素值是否相等
代碼示例
print("---")
# 定義元素
tuple1 = (1, 2, 3, 4)
tuple2 = (4, 3, 2, 1)
tuple3 = (1, 2, 3, 4)
print("tuple{} 與 tuple{} 相等? {}".format(tuple1, tuple2, tuple1 == tuple2))
print("tuple{} 與 tuple{} 相等? {}".format(tuple1, tuple3, tuple1 == tuple3))
print("tuple{} 與 tuple{} 相等? {}".format(tuple2, tuple3, tuple2 == tuple3))
print("---")---
tuple(1, 2, 3, 4) 與 tuple(4, 3, 2, 1) 相等? False
tuple(1, 2, 3, 4) 與 tuple(1, 2, 3, 4) 相等? True
tuple(4, 3, 2, 1) 與 tuple(1, 2, 3, 4) 相等? False
---
in tuple成員判斷基本語法
boolean_var = element in tuple功能:使用 "in" 操作符來判斷元素是否存在於tuple中, 若存在返回值為布爾類型 True, 否則返回 False。
代碼示例
natural_numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
test_numbers = (1, 3, 9,12)
for ix, number in enumerate(test_numbers):
if number in natural_numbers: # 判斷是否在集合中
print("the {}-th element {} is in numbers {}".format(ix , number, numbers))
else:
print("the {2}-th element {0} is not in numbers {1}".format(number, numbers ,ix))the 0-th element 1 is in numbers (-1, -2, -3)
the 1-th element 3 is in numbers (-1, -2, -3)
the 2-th element 9 is in numbers (-1, -2, -3)
the 3-th element 12 is not in numbers (-1, -2, -3)
tuple 常用methodtuple是一種靜態的數據類型, 不可以對tuple執行修改等操作, tuple中提供的方法主要是對元素進行查找。
notes:與之對應的,list是一種動態的數據類型,可以通過[]對list中的元素進行修改
tuple元素 修改 tuple元素 查找統計(1)index方法
class tuple(object):
def index(self, *args, **kwargs): # real signature unknown
"""
Return first index of value.
Raises ValueError if the value is not present.
"""
pass基本語法
tuple_test = (1,'a', true ) # 定義一個tuple
tuple_test.index( 'a') # 獲取 tuple_test 中'a'的index功能:在tuple中查找元素是否存在, 如果存在會返回該元素的索引, 如果不存在會拋出ValueError 。
代碼示例
students = ('Lily', 'Lucy', 'xiao樂', 'Lily')
print('當前tuple{}中元素{}第1次出現的位置為{}'.format(students, 'Lily', students.index('Lily')))
print('當前tuple{}中元素{}在index{}以後 第1次出現的位置為{}'.format(students,
'Lily', 1, students.index('Lily', 1)))當前tuple('Lily', 'Lucy', 'xiao樂', 'Lily')中元素Lily第1次出現的位置為0
當前tuple('Lily', 'Lucy', 'xiao樂', 'Lily')中元素Lily在index1以後 第1次出現的位置為3(2)count方法
class tuple(object):
def count(self, *args, **kwargs): # real signature unknown
""" Return number of occurrences of value. """
pass基本語法
tuple_test = [1,'a', true , 'a'] # 定義一個tuple
tuple_test.count( 'a') # 獲取tuple_test 中'a'出現的次數功能:查找元素值 value 在tuple中出現的次數, 元素值 value 不存在時, 返回 0
代碼示例
students = ('Lily', 'Lucy', 'xiao樂', 'Lily')
element = 'Lily'
print("元素{} 在 tuple {} 中出現的次數為 {}".format(element, students, students.count(element)))
element1 = 'xiaoLe'
print("元素{} 在 tuple {} 中出現的次數為 {}".format(element1, students, students.count(element1)))元素Lily 在 tuple ('Lily', 'Lucy', 'xiao樂', 'Lily') 中出現的次數為 2
元素xiaoLe 在 tuple ('Lily', 'Lucy', 'xiao樂', 'Lily') 中出現的次數為 0
tuple vs list 不支持 item assignment or other mutation operations即傳說中的 immutable
不支持 item assignment or other mutation operation是指不可以對該數據類型進行修改,即只讀的數據類型,例如str、tuple
使用[]操作符對str、tuple進行賦值修改,Python會Raise Error
string = "xiaole很帥"
string[-1]="窮"TypeError Traceback (most recent call last)
<ipython-input-18-23ec473035e6> in <module>
1 string = "xiaole很帥"
----> 2 string[-1]="窮"
TypeError: 'str' object does not support item assignmenttuple_test = tuple( "你和我")
print(tuple_test )
tuple_test[-1]="她"
TypeError Traceback (most recent call last)
<ipython-input-21-41ebe686c69d> in <module>
1 tuple_test = tuple( "你和我")
2 print(tuple_test )
----> 3 tuple_test[-1]="她"
TypeError: 'tuple' object does not support item assignmentnotes:xiaole很窮?你和她? 統統都不存在的
支持 item assignment or other mutation operations即傳說中的 mutable
支持item assignment or other mutation operation 的數據類型中的元素是可以修改的,常用的動態數據類型包括list、dict、set、defaultdict等
通過**[]與=、或者set的add方法**等對數據容器中的元素進行修改,修改前後的列表與修改前的動態數據類型具有相同的id值
dict_test=dict( name = "xiaole", height=180 )
print("修改前:", dict_test, "===> id值" ,id(dict_test) )
dict_test["height"]=177
print("修改前:", dict_test, "===> id值" ,id(dict_test) )修改前: {'name': 'xiaole', 'height': 180} ===> id值 2330246949608
修改前: {'name': 'xiaole', 'height': 177} ===> id值 2330246949608set_test = set("你我")
print( set_test )
print(set_test.add("她"))
set_test.add("她")
print(set_test ){'我', '你'}
None
{'我', '你', '她'}
References[1] 菜鳥教程 Python 元組(Tuple) https://www.runoob.com/python/python-tuples.html
[2] 薯條老師Python系列 http://www.chipscoco.com/
Motto日拱一卒,功不唐捐
長按下圖 關注xiao樂