Python 進階之路 (一) List 進階方法彙總,新年快樂!

開啓變身模式

你們好, 從這一期開始,咱們會從小白變身爲中等小白,在基礎起步階段有太多的東西我沒有講到,可是俗話說的好,無他,但手熟爾,只要多多練習,時間會是最好的證實,相信咱們終有一天會成爲高手,所以從這一系列開始,讓咱們一塊兒更上一層樓,仍是和往常同樣,我也是水平不高,若是有大神發現文章中的錯誤必定要指出哈~segmentfault

先皮一下,看個歐陽修的<<賣油翁>>:微信

陳康肅公堯諮善射,當世無雙,公亦以此自矜。嘗射於家圃,有賣油翁釋擔而立,睨之,久而不去。見其發矢十中八九,但微頷之。

康肅問曰:「汝亦知射乎?吾射不亦精乎?」翁曰:「無他,但手熟爾。」康肅忿然曰:「爾安敢輕吾射!」翁曰:「以我酌油知之。」乃取一葫蘆置於地,以錢覆其口,徐以杓酌油瀝之,自錢孔入,而錢不溼。因曰:「我亦無他,唯手熟爾。」康肅笑而遣之。數據結構

List的進階用法

這裏我將會詳細介紹一些我認爲很是不錯的List的使用方法,至於list 自帶的一些基礎用法,這裏再也不說明,感興趣的朋友們能夠看看個人基礎教程: Python 基礎起步 (五) 必定要知道的數據類型:初識ListPython 基礎起步 (六) List的實用技巧大全, 好啦,閒話少說,讓咱們開始吧dom

把其餘類型數據結構轉化爲List類型

利用list(target)便可實現把其餘類型的數據結構轉化爲List類型,十分實用,咱們能夠把字符串,元組等數據結構轉化爲List,也能夠直接建立,像下圖同樣:ide

print(list())                            # 建立空List

vowelString = 'aeiou'                    # 把字符串轉化爲List
print(list(vowelString))

vowelTuple = ('a', 'e', 'i', 'o', 'u')  # 從元組tuple轉化爲List
print(list(vowelTuple))

vowelList = ['a', 'e', 'i', 'o', 'u']   # 從List到List
print(list(vowelList))

vowelSet = {'a', 'e', 'i', 'o', 'u'}    #  從Set到List
print(list(vowelSet))

Out: []
     ['a', 'e', 'i', 'o', 'u']
     ['a', 'e', 'i', 'o', 'u']
     ['a', 'e', 'i', 'o', 'u']
     ['a', 'e', 'i', 'o', 'u']

可能平時用的比較多的通常是從一個dict中提取 keys 和 values :函數

person = {
    'name':'Peppa Pig',
    'age':15,
    'country':'bratian'}

person_keys = list(person.keys())
person_values = list(person.values())

print(list(person))  # 若是直接轉化一個字典只會把keys提取出來
print(list(person.keys()))
print(list(person.values()))

Out:['name', 'age', 'country']    
    ['name', 'age', 'country']             # 把字典中的Keys提出
    ['Peppa Pig', 15, 'bratian']           # 把字典中的Values提出

這裏你們稍微注意下,若是直接用list(person)會默認等同於person.keys()spa

List排序方法彙總

整體來講,有兩種方法最爲便捷,List.sort 或者 sorted(List),具體來看如何實現,先看升序:code

vowels = ['e', 'a', 'u', 'o', 'i']   
vowels.sort()        
print('Sorted list Acending:', vowels)  # 使用sort
Out: Sorted list Acending: ['a', 'e', 'i', 'o', 'u']
vowels = ['e', 'a', 'u', 'o', 'i']   
print('Sorted list Acending:', sorted(vowels))  # 使用sorted
Out:Sorted list Acending: ['a', 'e', 'i', 'o', 'u']

再來看降序:排序

vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort(reverse=True)     # 使用sort
print('Sorted list (in Descending):', vowels)
Out: Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']
vowels = ['e', 'a', 'u', 'o', 'i']
print('Sorted list (in Descending):', sorted(vowels,reverse=True))  # 使用sorted方法
Out:Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

其實這裏裏面還有一個關鍵的參數是key,咱們能夠自定義一些規則排序,下面看個例子,用的是默認的len函數
,讓咱們根據List中每一個元素的長度來排序,首先是升序:教程

vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
# 使用sort
vowels.sort(key=len)  
print('Sorted by lenth Ascending:', vowels)
Out:Sorted by lenth: ['I', 'I', 'at', 'live', 'love', 'Paris', 'Python']
vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
# 使用 sorted
print('Sorted by lenth Ascending:', sorted(vowels,key=len))
Out:Sorted by lenth Ascending: ['I', 'I', 'at', 'live', 'love', 'Paris', 'Python']

降序也差很少啦:

vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
vowels.sort(key=len,reverse=True)
print('Sorted by lenth Descending:', vowels)
Out:Sorted by lenth Descending: ['Python', 'Paris', 'live', 'love', 'at', 'I', 'I']
vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
print('Sorted by lenth Descending:', sorted(vowels,reverse=True))
Out:Sorted by lenth Descending: ['Python', 'Paris', 'live', 'love', 'at', 'I', 'I']

有關這個key咱們能夠本身定義,請看下面的大栗子:

def takeSecond(elem):
    return elem[1]

random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond) # sort list with key
print('Sorted list:', random)

Out: [(4, 1), (2, 2), (1, 3), (3, 4)]

這裏由於列表中的元素都是元組,因此咱們規定按照元組的第二個數排序,因此結果如上,默認依然是reverse=False ,也就是升序,至於其餘有意思的方法你們能夠本身開發

逆序輸出List

若是咱們想要逆序輸出一個List,簡單來講有兩種方法比較好用,切片和reverse,來看例子:

vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
    print(list(reversed(vowels)))
    print(list[::-1])
Out:['Python', 'love', 'I', 'Paris', 'at', 'live', 'I']   
    ['Python', 'love', 'I', 'Paris', 'at', 'live', 'I']
利用Range生成List

Python裏面爲咱們提供了一個超好用的方法range(),具體的用法不少,不在這裏一一講解啦,可是你們能夠看一下它如何和List結合在一塊兒的:

five_numbers=list(range(5))  #建立0~4的List
print(five_numbers)

odd_numbers=list(range(1,50,2))   #建立0~50全部的奇數的List
print(odd_numbers)

even_numbers=list(range(0,50,2))  #建立0~50全部的偶數的List
print(even_numbers)

其實很簡單,用的最多的就是range(start, stop, hop)這個結構,其餘的你們能夠自行查詢哈

List列表推導式

其實這個東西無非就是爲了減小代碼書寫量,比較Pythonic的東西,基礎模板以下:

variable = [out_exp for out_exp in input_list if out_exp == 2]

你們直接看比較麻煩,仍是直接上代碼吧:

S = [x**2 for x in range(8)]      # 0~7每一個數的平方存爲List
V = [2**i for i in range(8)]      # 2的 0~7次方
M = [x for x in S if x % 2 == 0]  #找出在S裏面的偶數

print(S)
print(V)
print(M)


Out:   Square of 0 ~7:  [0, 1, 4, 9, 16, 25, 36, 49]
       The x power of 2,(0<x<7) :  [1, 2, 4, 8, 16, 32, 64, 128]
       The even numbers in S:  [0, 4, 16, 36]

經過這個小栗子你們估計已經明白用法啦,推導式還能夠這麼用:

verbs=['work','eat','sleep','sit']
verbs_with_ing=[v+'ing' for v in verbs]   # 使一組動詞成爲如今分詞
print(verbs_with_ing)

Out:['working', 'eating', 'sleeping', 'siting']

或者加上查詢條件if :

all_numbers=list(range(-7,9))
numbers_positive = [n for n in all_numbers if n>0 ]
numbers_negative = [n for n in all_numbers if n<0]
devided_by_two = [n for n in all_numbers if n%2==0]

print("The positive numbers between -7 to 9 are :",numbers_positive)
print("The negative numbers between -7 to 9 are :",numbers_negative )
print("The numbers deveided by 2 without reminder are :",devided_by_two)```

Out:The positive numbers between -7 to 9 are : [1, 2, 3, 4, 5, 6, 7, 8]
     The negative numbers between -7 to 9 are : [-7, -6, -5, -4, -3, -2, -1]
     The numbers deveided by 2 without reminder are : [-6, -4, -2, 0, 2, 4, 6, 8]

總結

其實客觀來說,list在實際項目中所用的地方有限,特別是處理數據量較大的狀況下,由於速度極慢,可是在一些邊邊角角的地方我我的用的還挺多,尤爲是不求速度的地方,總的來說List是我我的比較喜歡的Python
數據結構,簡單好用!!!!!

若是你們對List的其餘使用技巧感興趣,能夠關注個人微信公衆號Python極簡教程,我會把最高效,簡潔的小技巧一一記錄下來,分享給你們:

圖片描述

相關文章
相關標籤/搜索