萬(wàn)能Python的秘訣:操縱數(shù)據(jù)的內(nèi)置工具
本文轉(zhuǎn)載自公眾號(hào)“讀芯術(shù)”(ID:AI_Discovery)。
Python可謂是如今最流行的編程語(yǔ)言,甚至孩子們也可以從它開(kāi)始學(xué)習(xí)趣味編程。Python類似英語(yǔ)的簡(jiǎn)單語(yǔ)法使它成為一種通用語(yǔ)言,已在全世界各個(gè)領(lǐng)域被廣泛使用。
Python的萬(wàn)能之處正在于其內(nèi)置的數(shù)據(jù)結(jié)構(gòu),它使編碼變得簡(jiǎn)單,不受數(shù)據(jù)類型限制,并可以根據(jù)需要操縱數(shù)據(jù)。
首先,讓我們?cè)囍斫馐裁词菙?shù)據(jù)結(jié)構(gòu)?數(shù)據(jù)結(jié)構(gòu)是能夠存儲(chǔ)、組織和管理數(shù)據(jù)的結(jié)構(gòu)/容器,以便能夠有效地訪問(wèn)和使用數(shù)據(jù)。數(shù)據(jù)結(jié)構(gòu)就是收集數(shù)據(jù)類型。Python中有四種內(nèi)置數(shù)據(jù)結(jié)構(gòu)。它們是:
- 列表
- 字典
- 元組
- 集合
開(kāi)發(fā)人員最常用的數(shù)據(jù)結(jié)構(gòu)是列表和字典。接下來(lái),讓我們?cè)敿?xì)看看每一個(gè)數(shù)據(jù)結(jié)構(gòu)。
1. 列表
Python列表是按順序排列的任意類型的項(xiàng)的集合。一個(gè)列表可以有重復(fù)的項(xiàng),因?yàn)槊總€(gè)項(xiàng)都是使用索引訪問(wèn)的,而且可以通過(guò)使用負(fù)索引逆向訪問(wèn)該列項(xiàng)。列表是可變的,這意味著即使在創(chuàng)建了項(xiàng)之后,也可以添加、刪除或更改項(xiàng);一個(gè)列表中還可以包含另一個(gè)列表。
(1) 創(chuàng)建列表:
列表可以通過(guò)將元素括在[ ]方括號(hào)中來(lái)創(chuàng)建,每個(gè)項(xiàng)之間用逗號(hào)分隔。以購(gòu)物清單為例,創(chuàng)建列表的語(yǔ)法是:
- #Creating a list fruits = ['Apple', 'Banana', "Orange"]
- print(type(fruits)) #returns type
- print(fruits) #prints the elements of the listOutput:
- <class 'list'>
- ['Apple', 'Banana', 'Orange']
(2) 訪問(wèn)列表:
可以使用索引訪問(wèn)列表中的項(xiàng)。列表中的每個(gè)項(xiàng)都有一個(gè)與之關(guān)聯(lián)的索引,具體取決于該項(xiàng)在列表中的位置。訪問(wèn)列表中的項(xiàng)的語(yǔ)法:
- #Access elements in the fruits listfruits = ['Apple', 'Banana',"Orange"]
- print(fruits[0]) #index 0 is the first element
- print(fruits[1])
- print(fruits[2])Output:
- Apple
- Banana
- Orange
但是,索引不必總是為正。如果想逆向訪問(wèn)列表,也就是按照相反的順序,可以使用負(fù)索引,如下所示:
- #Access elements in the fruits list using negative indexesfruits = ['Apple','Banana', "Orange"]
- print(fruits[-1]) #index -1 is the last element
- print(fruits[-2])
- print(fruits[-3])Output:
- Orange
- Banana
- Apple
如果必須返回列表中兩個(gè)位置之間的元素,則使用切片。必須指定起始索引和結(jié)束索引來(lái)從列表中獲取元素的范圍。語(yǔ)法是List_name[起始:結(jié)束:步長(zhǎng)]。在這里,步長(zhǎng)是增量值,默認(rèn)為1。
- #Accessing range of elements using slicingfruits = ['Apple', 'Banana',"Orange"]
- fruits #all elements
- ['Apple', 'Guava', 'Banana', 'Kiwi'] #output
- fruits[::1] #start to end with step 1
- ['Apple', 'Guava', 'Banana', 'Kiwi'] #outputfruits[::2] #start to endwith step 2 basically index 0 & 2
- ['Apple', 'Banana'] #output
- fruits[::3] #start to end with step 2 basically index 0 & 3
- ['Apple', 'Kiwi'] #output
- fruits[::-1] #start to end with step 2 - reverse order
- ['Kiwi', 'Banana', 'Guava', 'Apple'] #output
(3) 向列表中添加元素:
可以使用append()、extend()和insert()函數(shù)向列表添加項(xiàng)。
- #Adding elementsfruits = ['Apple', 'Banana', "Orange"]#Appendnew elements
- fruits.append('Kiwi')
- print(fruits)
- Output:
- ['Apple', 'Banana', 'Orange', 'Kiwi']#Insertelements in to the listfruits.insert(1,'Guava') #inserts Guava as secondelement is the list since the index is specified as 1
- print(fruits)
- Output:
- ['Apple', 'Guava', 'Banana','Orange', 'Kiwi']
(4) 從列表中刪除項(xiàng):
與添加元素類似,從列表中刪除元素也非常容易,可以使用del()、remove()和pop()方法實(shí)現(xiàn)。要清除整個(gè)列表,可以使用clear()函數(shù)。
- del()函數(shù)刪除給定索引處的元素。
- pop()函數(shù)從列表中刪除給定索引處的元素,也可以將刪除的元素賦值給變量。如果未指定索引值,則刪除列表中的最后一個(gè)元素。
- remove()函數(shù)根據(jù)元素的值來(lái)刪除元素。
- clear()函數(shù)清空列表。
- #Deleting elements from the listfruits = ['Apple', 'Guava', 'Banana','Orange', 'Kiwi']
- #del() function
- del fruits[3] #delete element at index 4
- print(fruits)
- Output:
- ['Apple', 'Guava', 'Banana', 'Kiwi']#pop()function
- del_fruit = fruits.pop(2)
- print(del_fruit)
- print(fruits)
- Output:
- 'Banana'
- ['Apple', 'Guava', 'Orange', 'Kiwi']
- #Remove function
- fruits.remove('Apple')
- print(fruits)
- Output:
- ['Guava', 'Banana', 'Orange', 'Kiwi']
- #Clear() function
- fruits.clear()
- print(fruits)
- Output :
- [] # clears the list
其他函數(shù):
在處理列表時(shí),還可以使用其他幾個(gè)函數(shù):
- len()函數(shù)返回列表的長(zhǎng)度。
- index()函數(shù)查找第一次遇到的傳入值的索引值。
- count()函數(shù)查找傳遞給它的值的個(gè)數(shù)。
- sorted()和sort()函數(shù)用于對(duì)列表的值進(jìn)行排序。sorted()具有返回類型,而sort()修改原始列表。
- #Other functions for listnum_list = [1, 2, 3, 10, 20, 10]
- print(len(num_list)) #find length of list
- print(num_list.index(10)) #find index of element that occurs first
- print(num_list.count(10)) #find count of the element
- print(sorted(num_list)) #print sorted list but not change original
- num_list.sort(reverse=True) #sort original list
- print(num_list)Output:
- 6
- 3
- 2
- [1, 2, 3, 10, 10, 20]
- [20, 10, 10, 3, 2, 1]
2. 字典
字典是另一種無(wú)序的數(shù)據(jù)結(jié)構(gòu),即元素的存儲(chǔ)順序與它們被插入的順序不同。這是因?yàn)樗饕挡荒茉L問(wèn)字典中的元素。在字典中,數(shù)據(jù)以鍵值對(duì)的形式存儲(chǔ),元素值是通過(guò)鍵訪問(wèn)的。
圖源:unsplash
(1) 創(chuàng)建字典:
字典由冒號(hào)分隔的{}大括號(hào)或使用dict()函數(shù)編寫鍵和值被創(chuàng)建。
- #Creating Dictionariesnew_dict = {} #empty dictionary
- print(new_dict)
- new_dict = {1: 'Python', 2: 'Java'} #dictionary with elements
- print(new_dict)Output:
- {}
- {1: 'Python', 2: 'Java'}
(2) 改變并增加鍵值對(duì):
要更改字典的值,將使用鍵來(lái)訪問(wèn)鍵,然后相應(yīng)地更改值。要添加值,只需添加另一個(gè)鍵-值對(duì),如下所示:
- #Changing and Adding key, value pairslang_dict = {'First': 'Python','Second': 'Java'}
- print(lang_dict)
- lang_dict['Second'] = 'C++' #changing element
- print(lang_dict)
- lang_dict['Third'] = 'Ruby' #adding key-value pair
- print(lang_dict)Output:
- {'First': 'Python', 'Second': 'Java'}
- {'First': 'Python', 'Second': 'C++'}
- {'First': 'Python', 'Second': 'C++','Third': 'Ruby'}
(3) 訪問(wèn)字典中的元素:
字典中的元素只能使用鍵訪問(wèn),可以使用get()函數(shù)或只是通過(guò)鍵來(lái)獲取值。
- #Accessing Elementslang_dict = {'First': 'Python', 'Second': 'Java'}
- print(lang_dict['First']) #access elements using keys
- print(lang_dict.get('Second'))Output:
- Python
- Java
(4) 刪除字典中的鍵值對(duì):
這些是字典中用于刪除元素的函數(shù)。
- pop()-刪除值并返回已刪除的值
- popitem()-獲取鍵值對(duì)并返回鍵和值的元組
- clear()-清除整個(gè)字典
- #Deleting key, value pairs in a dictionarylang_dict = {'First': 'Python','Second': 'Java', 'Third': 'Ruby'}
- a = lang_dict.pop('Third') #pop element
- print('Value:', a)
- print('Dictionary:', lang_dict)
- b = lang_dict.popitem() #pop the key-value pair
- print('Key, value pair:', b)
- print('Dictionary', lang_dict)
- lang_dict.clear() #empty dictionary
- print(lang_dict)Output:
- Value: Ruby #pop element
- Dictionary: {'First': 'Python','Second': 'Java'}
- Key, value pair: ('Second', 'Java') #popthe key-value pair
- Dictionary {'First': 'Python'}
- {} #empty dictionary
(5) 其他函數(shù):
這是其他一些可以與字典一起使用的函數(shù),用于獲取鍵值和鍵-值對(duì)等。
- #Other functions for dictionarylang_dict = {'First': 'Python','Second': 'Java', 'Third': 'Ruby'}
- print(lang_dict.keys()) #get keys
- print(lang_dict.values()) #get values
- print(lang_dict.items()) #get key-value pairs
- print(lang_dict.get('First'))Output:
- dict_keys(['First', 'Second','Third'])
- dict_values(['Python', 'Java','Ruby'])
- dict_items([('First', 'Python'),('Second', 'Java'), ('Third', 'Ruby')])
- Python
3. 元組
圖源:unsplash
元組與列表基本相同,不同的是,一旦數(shù)據(jù)進(jìn)入元組,無(wú)論如何都不能更改。因此,一旦生成元組,就不能添加、刪除或編輯任何值。
(1) 創(chuàng)建元組:
使用()圓括號(hào)或tuple()函數(shù)創(chuàng)建元組。
- #Creating Tuplesmy_tuple = (1, 2, 3) #create tupleprint(my_tuple)Output: (1, 2, 3)#Creating Tuplesmy_tuple = (1, 2, 3) #create tuple
- print(my_tuple)Output:
- (1, 2, 3)
(2) 訪問(wèn)元組中的元素:
訪問(wèn)元組元素與列表類似。
- #access elementsmy_tuple2 = (1, 2, 3,'new') for x in my_tuple2:
- print(x) # prints all the elementsin my_tuple2print(my_tuple2)
- print(my_tuple2[0]) #1st element
- print(my_tuple2[:]) #all elements
- print(my_tuple2[3][1]) #this returns the 2nd character of the element atindex 3
- print(my_tuple2[-1]) #last elementOutput:
- 1
- 2
- 3
- new
- (1, 2, 3, 'new')
- 1
- (1, 2, 3, 'new')
- e
- new
(3) 在另一元組中追加元素:
要追加值,可以使用'+'操作符。
- #Appending elementsmy_tuple = (1, 2, 3)
- my_tuplemy_tuple = my_tuple + (4, 5, 6) #add elements
- print(my_tuple)Output:
- (1, 2, 3, 4, 5, 6)
(4) 元組賦值:
元組打包和解包操作很有用,執(zhí)行這些操作可以在一行中將另一個(gè)元組的元素賦值給當(dāng)前元組。元組打包就是通過(guò)添加單個(gè)值來(lái)創(chuàng)建元組,元組拆包則是將元組中的值分配給變量。
- #tuple packing
- planets = ('Earth','Mars','Jupiter')
- #tuple unpackinga,b,c = planets
- print(a)
- print(b)
- print(c)Output:
- Earth
- Mars
- Jupiter
4. 集合
圖源:unsplash
集合是唯一的無(wú)序元素的集合。這意味著,即使數(shù)據(jù)重復(fù)一次以上,集合也只保留一次。
(1) 創(chuàng)建集合:
使用{ }花括號(hào)創(chuàng)建集合,并賦值。
- #Creating setsnew_set = {1, 2, 3, 4, 4, 4, 5} #create set
- print(new_set)Output:
- {1, 2, 3, 4, 5}
(2) 向集合中添加元素:
使用add()函數(shù)賦值并添加元素。
- #Adding elements to a Setnew_set = {1, 2, 3}
- new_set.add(4) #add element to set
- print(new_set)Output:
- {1, 2, 3, 4}
(3) 集合操作:
可以對(duì)一個(gè)集合執(zhí)行的不同操作如下所示。
- union()函數(shù)合并了兩個(gè)集合中的數(shù)據(jù)。
- intersection()函數(shù)只查找在這兩個(gè)集合中同時(shí)出現(xiàn)的數(shù)據(jù)。
- difference()函數(shù)刪除兩個(gè)集合中同時(shí)存在的數(shù)據(jù),并只輸出在傳遞的集合中存在的數(shù)據(jù)。
- symmetric_difference()函數(shù)執(zhí)行與difference()函數(shù)相同的操作,但是輸出在兩個(gè)集合中保留的數(shù)據(jù)。
- clear()函數(shù)清空該集合。
- #Operations on set
- my_set = {1, 2, 3, 4}
- my_set_2 = {3, 4, 5, 6}
- print(my_set.union(my_set_2))
- print(my_set.intersection(my_set_2))
- print(my_set.difference(my_set_2))
- print(my_set.symmetric_difference(my_set_2))
- my_set.clear()
- print(my_set)Output:
- {1, 2, 3, 4, 5, 6}
- {3, 4}
- {1, 2}
- {1, 2, 5, 6}
- set()
Python為我們有效管理、組織和訪問(wèn)數(shù)據(jù)提供了多種選項(xiàng),學(xué)習(xí)其基本內(nèi)置數(shù)據(jù)結(jié)構(gòu)是Python學(xué)習(xí)之旅非常關(guān)鍵的一環(huán)。