數據容器 tuple

2021-03-02 xiao樂
數據容器 tuple數據容器之tuplelist 定義 list基本概念

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 組成的tuple
print("-- 利用 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 常用method

tuple是一種靜態的數據類型, 不可以對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 assignment

tuple_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 assignment

notes: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值 2330246949608

set_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樂


相關焦點

  • C++(STL):02---tuple容器
    類模板//item的類型為tuple<const char*, int, double>auto item = std::make_tuple("0-999-78345-X", 3, 20.00);//trans為item的數據類型typedef decltype(item) trans;//返回item
  • 元組(tuple)-Python基本數據類型之四
    在python中,元組這種數據結構同列表類似,都可以描述一組數據的集合,它們都是容器,是一系列組合的對象,不同的地方在於,元組裡的元素是不能更改的,它們之間的差異性我們用一個例子來說明一下:列表:>元組:>>> student=(1,"tom","2008-05-06",10,135.7)>>> print(student[1]) #輸出 tom從上面的比較例子可以看出,列表一般用於不確定個數的數據的集合中
  • Python基礎數據類型——tuple淺析
    有序列表叫元組:tuple。tuple和list非常類似,但是tuple一旦初始化就不能修改。二、用法1. tuple元組的定義Python的元組與列表類似,不同之處在於元組的元素不能修改。元組使用小括號,列表使用方括號。
  • Python數據類型之元組tuple
    # 元組(tuple)是 Python 中另一個重要的序列結構,和列表類似,元組也是由一系列按特定順序排序的元素組成。
  • 數據類型介紹——tuple、list和range對象
    )(1)定義元組元組使用圓括號「()」與逗號「,」來創建,同樣可以包含任意數據類型,其定義方法主要有以下幾種:In [15]: 1,'python',2.3In [16]: tuple_1Out[16]: (1, 'python', 2.3)也可以由括號直接定義:
  • python學習|tuple數據結構詳解
    tuple1 = (1,2)print(tuple1)tuple2=(1,2,"qzq")print(tuple2)# 元組只有一個元素時,需要加一個逗號tuple3=(1,)print(tuple3)# 第1個元素數字
  • python3.6中數據類型之list和tuple的比較
    list使用中括號,有序,可修改其中的數值tuple使用小括號,有序,不可修改其中的數值我們分別定義一個list,一個tuple.list = [10,8.9,"first milk_tea of autumn",1-2j]tuple=(10,8.9,"first milk_tea of autumn",1-2j)我們可以看出,每個裡面都放了四個數據,分別是整型10,浮點型8.9,字符串型first milk_tea of autumn,複數 1-2j我們如何存取。
  • 從零開始學Python-Day9-集合list和元組tuple
    刪除末尾元素 pop刪除指定位置元素 pop替換指定位置元素直接向指定索引位置賦值效果如下:list內部的元素可以是不同數據類型如果一個list為空,即裡面沒有元素,那麼他的長度也就len應該等於0tupletuple叫做元組,它跟list最大的區別就是一旦初始化就不允許再變化,所謂初始化就是給它賦值。
  • Python的List與Tuple
    List(列表)List(列表) 是 Python 中使用最頻繁的數據類型。列表可以完成大多數集合類的數據結構實現。列表中元素的類型可以不相同,它支持數字,字符串甚至可以包含列表(所謂嵌套)。列表是寫在方括號([])之間、用逗號分隔開的元素列表。
  • Objective-C的元組實現(JDTuple)
    我們在使用字典或數組時,總是需要判斷數組越界,判斷數據是否為空,判斷數據類型。有沒有覺得定義多參數函數的時候特別雜亂無章?有沒有覺得Swift的元組使用起來特別順心?這些問題其實都源於OC是一門比較古老的語言,早期設計時缺少一個足夠靈活,足夠好用的數據封裝工具。
  • python中namedtuple與OrderedDict 的使用
    今天來講解一下python中的 Namedtuple與OrderedDict 的使用。一、Namedtuple我們都知道,在python的數據結構裡,tuple(元組)表示的是不可變集合。比如,一個點的二維坐標可以表示為:p = (1, 2)但是,當看到(1,2)的時候,我們很難看得出這個tuple是用來表示一個坐標的。
  • 好冷的Python–tuple和逗號的糾纏
    ", line 9, in <module> sum = sum + cTypeError: can only concatenate tuple (not "int") to tuple運行文件居然拋異常了,提示「sum = sum + c」 這一行中有TypeError,意思是只能用tuple和tuple相加,不能用int和tuple相加
  • 使用namedtuple的小例子
    今日分享namedtuple幹啥用from collections import namedtuplelst = [
  • 2.1 Python基礎知識(List和Tuple)
    一、List類型1.python創建List說明:Python內置的一種數據類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。構造list非常簡單,按照上面的代碼,直接用 [ ] 把list的所有元素都括起來,就是一個list對象。由於Python是動態語言,所以list中包含的元素並不要求都必須是同一種數據類型。
  • Python中比元組更好用的namedtuple
    其他內置函數(all、any、max、min、list、tuple、enumerate、sorted等)◆ 最大的痛點是只能通過數字索引來取值◆ 當元組中元素非常大時,通過索引取值非常不方便將測試數據從Excel(csv、json、資料庫)中讀取出來,在Python中處理時,往往可以使用namedtuple來承載數據。需要使用元組來處理數據的所有場景都可以。
  • Python入門14-元組tuple
    另一種有序列表叫元組(tuple)。tuple和list非常類似,但是tuple一旦初始化就不能修改。
  • 揭秘JavaScript的全新類型之Record和Tuple
    在這個博客文章中,我們首先看看ECMAScript提案"Record&Tuple"(https://github.com/tc39/proposal-record-tuple)。對象轉換為Record或Tuple> Record({x: 1, y: 4}) #{x: 1, y: 4}> Tuple.from(['a', 'b'])#['a', 'b']提示:如果數據中的任何節點不是基元
  • Python基礎篇——關於元組(tuple)和列表(list)區別
    一、前言在Python數據類型中有兩個對象:元組 tuple 和列表 list 。二者寫法和用法十分相似,有的同學就會去網上查找它們之間的區別,查到的無非以下幾種說法:list 是可變的,元組 tuple 是不可變的。由於 tuple 不可變,所以使用 tuple 可以使代碼更安全。等等 ...
  • Python基礎全套教程 8:Tuple元組學習(小白必看,系統學)
    也可以截取索引中的一段元素如下所示:L=('Google', 'Python', 'Taobao')Python表達式 結果描述L[2]'Taobao'讀取第三個元素L[-2]'Python'從右側開始讀取倒數第二個元素: count from the rightL[1:]('Python', 'Taobao')輸出從第二個元素開始後的所有元素元組內置函數:序號函數名稱說明1len(tuple
  • 如何在python中引入高性能數據類型?
    它們將 python 的功能擴展到許多流行的領域,包括機器學習、數據科學、web 開發、前端等等。其中最好的一個優點是 python 的內置 collections 模塊。在一般意義上,python 中的集合是用於存儲數據集合(如 list、dict、tuple 和 set)的容器。這些容器直接構建在 python 中,可以直接調用。