python數據結構 Python 列表深淺複製詳解

課程內容:html

  1. list 和 tuple 的運用
  2. str 的操做
  3. dict 和 set 的運用

1.list 和 tuple 的運用python

listgit

list(列表)是Python內置的一種數據類型,list是一種有序的集合,並且能夠對其中的元素進行增長、刪除等一系列操做。api

那麼,這裏定義一個list,來存放同窗的名字:數組

>>> students = ['Eric','Jack','Michael']
>>> students
['Eric', 'Jack', 'Michael']

變量 students 就是一個list,能夠經過下標訪問列表中的元素,下標從0開始計數: 安全

>>>students[0]
'Eric'
>>>students[1]
'Jack'
>>>students[-1] #還能夠倒着取,從-1開始
'Michael'
>>>students[-2]
'Jack'
>>>students[3]
Traceback (most recent call last):
  File "<stdin>", line 18, in <module>
IndexError: list index out of range

當下標超出了範圍時,Python會報一個IndexError錯誤,因此,要確保下標不要越界。app

len()函數能夠得到list元素的個數:ide

>>>len(students)
3

下面對列表進行一系列的操做函數

追加(到最後面):appendpost

>>>students.append('Bob')
>>>students
['Eric','Jack','Michael','Bob']
>>>students.append('最後一個')
>>>students
['Eric','Jack','Michael','Bob','最後一個']
View Code

 插入(到指定位置):insert

>>>students
['Eric', 'Jack', 'Michael', 'Bob', '最後一個']
>>>students.insert(2,'我要當第二')
>>>students
['Eric', 'Jack','我要當第二', 'Michael', 'Bob', '最後一個']
View Code

 刪除del、remove、pop

>>> del students[2]  #刪除指定下標元素
>>> students
['Eric', 'Jack', 'Michael', 'Bob', '最後一個']
>>> students.remove('Jack')  #刪除指定元素
>>> students
['Eric', 'Michael', 'Bob', '最後一個']
>>> students.pop()  #刪除列表最後一個值,並返回該值
'最後一個'
>>> students
['Eric', 'Michael', 'Bob']
>>> students.pop(1)  ##刪除指定下標元素,並返回該值
'Michael'
>>> students
['Eric', 'Bob']
View Code

 擴展與合併

>>> students=['Eric','Jack','Michael']
>>> L=[1,2,3]
>>> students.extend(L)   #擴展:將L添加到students的最後
>>> students
['Eric', 'Jack', 'Michael', 1, 2, 3]
>>>
>>>
>>>
>>> students=['Eric','Jack','Michael']
>>> L=[1,2,3]
>>> L+students   #合併:有先後順序
[1, 2, 3, 'Eric', 'Jack', 'Michael']
>>> students+L
['Eric', 'Jack', 'Michael', 1, 2, 3]
View Code

 替換

>>> students=['Eric','Jack','Michael']
>>> students[1]='Sarah'   #指定下標賦值
>>> students
['Eric', 'Sarah', 'Michael']
View Code

 多維列表(嵌套)

>>> p=['C++','C#']
>>> language=['C',p,'Java','PHP','Python']
>>> language
['C', ['C++', 'C#'], 'Java', 'PHP', 'Python']

 要拿到'C#'能夠寫p[1]或者language[1][1],所以language能夠當作是一個二維數組,相似的還有三維、四維……數組,不過不多用到。

>>> language[1][1]
'C#'

統計:count

>>> students=['Eric','Jack','Michael','Bob','Jack',11,12]
>>> students.count('Jack')   #統計Jack的數量
2
View Code

排序和翻轉:sort & reverse

>>> students=['Eric','Jack','Michael','Bob','Jack',11,12]
>>> students.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'   #不一樣數據類型不能放在一塊兒排序
>>> students[-1]='12'
>>> students[-2]='11'
>>> students
['Bob', 'Eric', 'Jack', 'Jack', 'Michael', '11', '12']
>>> students.sort()
>>> students
['11', '12', 'Bob', 'Eric', 'Jack', 'Jack', 'Michael']
>>>
>>>
>>> students.reverse()   #翻轉
>>> students
['Michael', 'Jack', 'Jack', 'Eric', 'Bob', '12', '11']
View Code

獲取下標

>>> students
['Michael', 'Jack', 'Jack', 'Eric', 'Bob', '12', '11']
>>> students.index('Jack')
1   #只返回找到的第一個下標
View Code

 複製:copy

>>> students=['Eric','Jack','Bob','Sarah','Michael']
>>> students1=students.copy()
>>> students1
['Eric', 'Jack', 'Bob', 'Sarah', 'Michael']
View Code

copy沒那麼簡單,詳細請轉    Python 列表深淺複製詳解

tuple

 另外一種有序列表叫元組:tuple。tuple和list很是相似,可是tuple一旦初始化就不能修改,好比一樣是列出同窗的名字:

>>> students = ('Eric','Jack','Michael')

如今,students這個tuple不能變了,它沒有增長、插入、修改、刪除元素、排序的操做,只有count()和index()的操做。

不可變的tuple有什麼意義?由於tuple不可變,因此代碼更安全。若是可能,能用tuple代替list就儘可能用tuple。

tuple的注意點:在定義的時候,tuple的元素就必須被肯定下來,好比:

>>>t=(6,8)
>>>t
(6,8)

但要定義只有一個元素的tuple時,若是你這樣定義:

>>> t=(6)
>>> t
6

定義的不是tuple,是1這個數!這是由於括號()既能夠表示tuple,又能夠表示數學公式中的小括號,這就產生了歧義,所以,Python規定,這種狀況下,

按小括號進行計算,計算結果天然是1

因此,只有1個元素的tuple定義時必須加一個逗號,,來消除歧義:

>>> t=(6,)
>>> t
(6,)

Python在顯示只有1個元素的tuple時,也會加一個逗號,,以避免你誤解成數學計算意義上的括號。

 

2.字符串的操做

>>> str='pyTHON'
>>> str.capitalize()  #返回一個首字母大寫的字符串。
'Python'
>>>a='1aPPLE'
>>>a.capitalize()    #首字符若是是非字母,首字母不會轉換成大寫,會轉換成小寫。
'1apple'
>>> str.center(20,'-')
'-------pyTHON-------'
>>> str.casefold()  #=str.lower(),全部字母變小寫
'python'
>>> str.count('T')   #統計字符個數
1
>>> str.encode()    #編碼爲指定的bytes
b'pyTHON'
>>> str.find('T')   #返回指定字符的下標
2
>>> str.find('A')    #若沒有該字符返回-1
-1
>>> str.index('H')   #返回指定字符的下標
3
>>> str.index('A')    #若沒有該字符則報錯
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> str.isdigit()   #判斷字符串是否只由數字組成
False
>>>b='123'
>>> b.isdigit()
True
>>> str.upper()    #將全部字母替換大寫
'PYTHON'
>>> c='   pyt  hon'
>>> c.strip()   #移除字符串頭尾指定的字符(默認爲空格或換行符)或字符序列,不能刪除中間部分的字符
'pyt  hon'

 

3.dict 和 set 的運用

dict

Python內置了字典:dict的支持,dict全稱dictionary,在其餘語言中也稱爲map,使用鍵-值(key-value)存儲。

這裏就再也不作鋪墊,直接來定義一個字典:(物品—價格)

>>> shop={'shoes':240,'T-shit':160,'pants':210}
>>> shop['pants']
210

直接根據商品名字查找價格,不管這個表有多大,查找速度都不會變慢。

爲何dict的查找速度這麼快?

爲了回答這個問題,咱們先來看下list:若是列表越大,那麼它的查找速度就越慢,由於列表是從第一個元素依次向後查找。

而字典則是根據給定的key值直接計算出對應value值的位置,直接取出便可。

這就好像兩我的查新華字典同樣,一我的是一頁一頁的翻着找,另外一我的則直接根據偏旁部首鎖定該字的頁碼。

增長:

>>> shop['hat']=60
>>> shop
{'shoes': 240, 'T-shit': 160, 'pants': 210, 'hat': 60}
View Code

字典中一個key只能對應一個value,若是屢次對一個key放入value,以前的值會被覆蓋(至關於修改):

>>> shop['scarf']=120
>>> shop
{'shoes': 240, 'T-shit': 160, 'pants': 210, 'hat': 60, 'scarf': 120}
>>> shop['scarf']=130
>>> shop
{'shoes': 240, 'T-shit': 160, 'pants': 210, 'hat': 60, 'scarf': 130}
View Code

若是key不存在,dict就會報錯

>>> shop['skirt']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'skirt'
View Code

要避免key不存在的錯誤,有兩種辦法,一是經過in判斷key是否存在;二是經過dict提供的get()方法,若是key不存在,能夠返回None,或者本身指定的value。

>>> 'skirt' in shop
False
>>>
>>>
>>> shop.get('skirt')   #注意:返回 None 的時候Python交互環境不顯示結果
>>> shop.get('skirt',-1)
-1
View Code

刪除:pop & del

>>> shop.pop('pants')    #刪除並返回value(推薦用pop)
210
>>> shop
{'shoes': 240, 'T-shit': 160, 'hat': 60, 'scarf': 130}


>>> del shop['shoes']    #刪除沒有返回值
>>> shop
{'T-shit': 160, 'hat': 60, 'scarf': 130}
View Code

多級字典嵌套及操做

dic={
   '河南':{
         '鄭州':
             ['金水區', '二七區'],
         '洛陽':
             ['澗西區', '洛龍區'],
         '信陽':
             ['溮河區', '平橋區']
    },
   '山東':{
          '濟南':
              ['槐蔭區', '歷下區'],
          '菏澤':
              ['牡丹區', '定陶區'],
          '淄博':
              ['臨淄區', '淄川區']
    },
   '湖北':{
         '武漢':
              ['江漢區', '漢陽區'],
          '咸寧':
              ['咸安區', '赤壁市'],
          '黃岡':
              ['黃州區', '鄂城區']
    }
}                
View Code

 5個方法

#values(以列表返回字典中的全部值)
>>> shop={'shoes':240,'T-shit':160,'pants':210}
>>> shop.values()
dict_values([240, 160, 210])


#keys(方法返回一個可迭代對象,可使用 list() 來轉換爲列表)
#注意:Python2.x 是直接返回列表
>>> shop.keys()
dict_keys(['shoes', 'T-shit', 'pants'])
>>> list(shop.keys())   #調用list()函數,轉換成列表
['shoes', 'T-shit', 'pants']


#setdefault(若key在字典中,返回對應的值。若不在字典中,則插入key及設置的默認值default,並返回default
>>> shop.setdefault('shoes',300)
240
>>> shop
{'shoes': 240, 'T-shit': 160, 'pants': 210}
>>> shop.setdefault('hat',90)
90
>>> shop
{'shoes': 240, 'T-shit': 160, 'pants': 210, 'hat': 90}
>>> shop.setdefault('gloves')   #default默認值爲None
>>> shop
{'shoes': 240, 'T-shit': 160, 'pants': 210, 'hat': 90, 'gloves': None}


#update(dict2 -- 添加到指定字典dict裏的字典)
>>> shop={'shoes': 240, 'T-shit': 160, 'pants': 210, 'hat': 90, 'gloves': None}
>>> info={'Eric':''}
>>> shop.update(info)
>>> shop
{'shoes': 240, 'T-shit': 160, 'pants': 210, 'hat': 90, 'gloves': None, 'Eric': ''}


#items(返回可遍歷的(鍵, 值) 元組數組)
>>> shop.items()
dict_items([('shoes', 240), ('T-shit', 160), ('pants', 210), ('hat', 90), ('gloves', None), ('Eric', '')])
View Code

請務必注意,dict內部存放的順序和key放入的順序是沒有關係的。

和list比較,dict有如下幾個特色:

  1. 查找和插入的速度極快,不會隨着key的增長而變慢;
  2. 須要佔用大量的內存,內存浪費多。

而list相反:

  1. 查找和插入的時間隨着元素的增長而增長;
  2. 佔用空間小,浪費內存不多。

因此,dict是用空間來換取時間的一種方法。

dict能夠用在須要高速查找的不少地方,在Python代碼中幾乎無處不在,正確使用dict很是重要,須要牢記的第一條就是dict的key必須是不可變對象

set

set和dict相似,不過set是一組key的集合,不存儲value。因爲key不能重複,因此,在set中,沒有重複的元素,固然集合天然是無序的。

要建立一個set,須要提供一個list做爲輸入:

>>> set1=set([1,3,5,7])   #注意定義的格式
>>> set1
{1, 3, 5, 7}

 若是定義set時有重複的key,set會自動過濾掉。

>>> set2=set([1,3,5,7,3,5])
>>> set2
{1, 3, 5, 7}

增長和刪除:add & remove

>>> set1.add(9)
>>> set1
{1, 3, 5, 7, 9}
>>>
>>>
>>> set1.remove(3)
>>> set1
{1, 5, 7, 9}

set能夠當作數學意義上的無序和無重複元素的集合,所以,兩個set能夠作數學意義上的交集、並集等操做:

>>> s=set([1,2,3,4])
>>> s
{1, 2, 3, 4}
>>> t=set([3,4,5,6])
>>> t
{3, 4, 5, 6}
#並集
>>> s.union(t)                      #姿式2:s | t
{1, 2, 3, 4, 5, 6}

#交集
>>> s.intersection(t)               #姿式2:s & t
{3, 4}

#差集(在s中,不在t中)
>>> s.difference(t)                 #姿式2:s - t
{1, 2}

#對稱差集(在s或在t中,不一樣時在)
>>> s.symmetric_difference(t)       #姿式2:s ^ t
{1, 2, 5, 6}

注意:set和dict的惟一區別僅在於沒有存儲對應的value,可是,set的原理和dict同樣,因此,一樣不能夠放入可變對象,由於沒法判斷兩個可變對象是否相等,

也就沒法保證set內部「不會有重複元素」,因此咱們能夠在set裏放一個list試試:

>>> L=[6,8]
>>> L
[6, 8]
>>> s=set([1,2,3,L,4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

若是把list放入set中,python就會報錯表示集合中不支持列表類型數據。

 

參考:

廖雪峯的官網

金角大王的博客

相關文章
相關標籤/搜索