萬能Python的秘訣:操縱資料的內建工具

萬能Python的秘訣:操縱資料的內建工具

圖源:unsplash

Python可謂是如今最流行的程式語言,甚至孩子們也可以從它開始學習趣味程式設計。Python類似英語的簡單語法使它成為一種通用語言,已在全世界各個領域被廣泛使用。

Python的萬能之處正在於其內建的資料結構,它使編碼變得簡單,不受資料型別限制,並可以根據需要操縱資料。

首先,讓我們試著理解什麼是資料結構?資料結構是能夠儲存、組織和管理資料的結構/容器,以便能夠有效地訪問和使用資料。資料結構就是收集資料型別。Python中有四種內建資料結構。它們是:

· 列表

· 字典

· 元組

· 集合

萬能Python的秘訣:操縱資料的內建工具

開發人員最常用的資料結構是列表和字典。接下來,讓我們詳細看看每一個數據結構。

萬能Python的秘訣:操縱資料的內建工具

列表

Python列表是按順序排列的任意型別的項的集合。一個列表可以有重複的項,因為每個項都是使用索引訪問的,而且可以透過使用負索引逆向訪問該列項。列表是可變的,這意味著即使在建立了項之後,也可以新增、刪除或更改項;一個列表中還可以包含另一個列表。

萬能Python的秘訣:操縱資料的內建工具

圖源:unsplash

建立列表:

列表可以透過將元素括在[ ]方括號中來建立,每個項之間用逗號分隔。以購物清單為例,建立列表的語法是:

#Creating a list fruits = [‘Apple’, ‘Banana’, “Orange”]print(type(fruits)) #returns typeprint(fruits) #prints the elements of the listOutput:        [‘Apple’, ‘Banana’, ‘Orange’]

訪問列表:

可以使用索引訪問列表中的項。列表中的每個項都有一個與之關聯的索引,具體取決於該項在列表中的位置。訪問列表中的項的語法:

#Access elements in the fruits listfruits = [‘Apple’, ‘Banana’,“Orange”]print(fruits[0]) #index 0 is the first elementprint(fruits[1])print(fruits[2])Output:    Apple    Banana    Orange

但是,索引不必總是為正。如果想逆向訪問列表,也就是按照相反的順序,可以使用負索引,如下所示:

#Access elements in the fruits list using negative indexesfruits = [‘Apple’,‘Banana’, “Orange”]print(fruits[-1]) #index -1 is the last elementprint(fruits[-2])print(fruits[-3])Output:    Orange    Banana    Apple

如果必須返回列表中兩個位置之間的元素,則使用切片。必須指定起始索引和結束索引來從列表中獲取元素的範圍。語法是List_name[起始:結束:步長]。在這裡,步長是增量值,預設為1。

#Accessing range of elements using slicingfruits = [‘Apple’, ‘Banana’,“Orange”]fruits #all elements [‘Apple’, ‘Guava’, ‘Banana’, ‘Kiwi’] #outputfruits[::1] #start to end with step 1[‘Apple’, ‘Guava’, ‘Banana’, ‘Kiwi’] #outputfruits[::2] #start to endwith step 2 basically index 0 & 2[‘Apple’, ‘Banana’] #outputfruits[::3] #start to end with step 2 basically index 0 & 3[‘Apple’, ‘Kiwi’] #outputfruits[::-1] #start to end with step 2 - reverse order[‘Kiwi’, ‘Banana’, ‘Guava’, ‘Apple’] #output

向列表中新增元素:

可以使用append()、extend()和insert()函式向列表新增項。

#Adding elementsfruits = [‘Apple’, ‘Banana’, “Orange”]#Appendnew elementsfruits。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 1print(fruits)Output:     [‘Apple’, ‘Guava’, ‘Banana’,‘Orange’, ‘Kiwi’]

從列表中刪除項:

與新增元素類似,從列表中刪除元素也非常容易,可以使用del()、remove()和pop()方法實現。要清除整個列表,可以使用clear()函式。

· del()函式刪除給定索引處的元素。

· pop()函式從列表中刪除給定索引處的元素,也可以將刪除的元素賦值給變數。如果未指定索引值,則刪除列表中的最後一個元素。

· remove()函式根據元素的值來刪除元素。

· clear()函式清空列表。

#Deleting elements from the listfruits = [‘Apple’, ‘Guava’, ‘Banana’,‘Orange’, ‘Kiwi’]#del() functiondel fruits[3] #delete element at index 4print(fruits)Output:     [‘Apple’, ‘Guava’, ‘Banana’, ‘Kiwi’]#pop()functiondel_fruit = fruits。pop(2)print(del_fruit)print(fruits)Output:     ‘Banana’      [‘Apple’, ‘Guava’, ‘Orange’, ‘Kiwi’]#Remove functionfruits。remove(‘Apple’)print(fruits)Output:     [‘Guava’, ‘Banana’, ‘Orange’, ‘Kiwi’]    #Clear() functionfruits。clear()print(fruits)Output :     [] # clears the list

其他函式:

在處理列表時,還可以使用其他幾個函式:

· len()函式返回列表的長度。

· index()函式查詢第一次遇到的傳入值的索引值。

· count()函式查詢傳遞給它的值的個數。

· sorted()和sort()函式用於對列表的值進行排序。sorted()具有返回型別,而sort()修改原始列表。

#Other functions for listnum_list = [1, 2, 3, 10, 20, 10]print(len(num_list)) #find length of listprint(num_list。index(10)) #find index of element that occurs firstprint(num_list。count(10)) #find count of the elementprint(sorted(num_list)) #print sorted list but not change originalnum_list。sort(reverse=True) #sort original listprint(num_list)Output:632[1, 2, 3, 10, 10, 20][20, 10, 10, 3, 2, 1]

萬能Python的秘訣:操縱資料的內建工具

字典

字典是另一種無序的資料結構,即元素的儲存順序與它們被插入的順序不同。這是因為索引值不能訪問字典中的元素。在字典中,資料以鍵值對的形式儲存,元素值是透過鍵訪問的。

萬能Python的秘訣:操縱資料的內建工具

圖源:unsplash

建立字典:

字典由冒號分隔的{}大括號或使用dict()函式編寫鍵和值被建立。

#Creating Dictionariesnew_dict = {} #empty dictionaryprint(new_dict)new_dict = {1: ‘Python’, 2: ‘Java’} #dictionary with elementsprint(new_dict)Output:    {}    {1: ‘Python’, 2: ‘Java’}

改變並增加鍵值對:

要更改字典的值,將使用鍵來訪問鍵,然後相應地更改值。要新增值,只需新增另一個鍵-值對,如下所示:

#Changing and Adding key, value pairslang_dict = {‘First’: ‘Python’,‘Second’: ‘Java’}print(lang_dict)lang_dict[‘Second’] = ‘C++’ #changing elementprint(lang_dict)lang_dict[‘Third’] = ‘Ruby’ #adding key-value pairprint(lang_dict)Output:    {‘First’: ‘Python’, ‘Second’: ‘Java’}    {‘First’: ‘Python’, ‘Second’: ‘C++’}    {‘First’: ‘Python’, ‘Second’: ‘C++’,‘Third’: ‘Ruby’}

訪問字典中的元素:

字典中的元素只能使用鍵訪問,可以使用get()函式或只是透過鍵來獲取值。

#Accessing Elementslang_dict = {‘First’: ‘Python’, ‘Second’: ‘Java’}print(lang_dict[‘First’]) #access elements using keysprint(lang_dict。get(‘Second’))Output:    Python    Java

刪除字典中的鍵值對:

這些是字典中用於刪除元素的函式。

· pop()-刪除值並返回已刪除的值

· popitem()-獲取鍵值對並返回鍵和值的元組

· clear()-清除整個字典

#Deleting key, value pairs in a dictionarylang_dict = {‘First’: ‘Python’,‘Second’: ‘Java’, ‘Third’: ‘Ruby’}a = lang_dict。pop(‘Third’) #pop elementprint(‘Value:’, a)print(‘Dictionary:’, lang_dict)b = lang_dict。popitem() #pop the key-value pairprint(‘Key, value pair:’, b)print(‘Dictionary’, lang_dict)lang_dict。clear() #empty dictionaryprint(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

其他函式:

這是其他一些可以與字典一起使用的函式,用於獲取鍵值和鍵-值對等。

#Other functions for dictionarylang_dict = {‘First’: ‘Python’,‘Second’: ‘Java’, ‘Third’: ‘Ruby’}print(lang_dict。keys()) #get keysprint(lang_dict。values()) #get valuesprint(lang_dict。items()) #get key-value pairsprint(lang_dict。get(‘First’))Output:    dict_keys([‘First’, ‘Second’,‘Third’])    dict_values([‘Python’, ‘Java’,‘Ruby’])    dict_items([(‘First’, ‘Python’),(‘Second’, ‘Java’), (‘Third’, ‘Ruby’)])    Python

元組

萬能Python的秘訣:操縱資料的內建工具

圖源:unsplash

元組與列表基本相同,不同的是,一旦資料進入元組,無論如何都不能更改。因此,一旦生成元組,就不能新增、刪除或編輯任何值。

建立元組:

使用()圓括號或tuple()函式建立元組。

#Creating Tuplesmy_tuple = (1, 2, 3) #create tupleprint(my_tuple)Output:    (1, 2, 3)#Creating Tuplesmy_tuple = (1, 2, 3) #create tupleprint(my_tuple)Output:    (1, 2, 3)

訪問元組中的元素:

訪問元組元素與列表類似。

#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 elementprint(my_tuple2[:]) #all elementsprint(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

在另一元組中追加元素:

要追加值,可以使用‘+’運算子。

#Appending elementsmy_tuple = (1, 2, 3)my_tuple = my_tuple + (4, 5, 6) #add elementsprint(my_tuple)Output:    (1, 2, 3, 4, 5, 6)

元組賦值:

元組打包和解包操作很有用,執行這些操作可以在一行中將另一個元組的元素賦值給當前元組。元組打包就是透過新增單個值來建立元組,元組拆包則是將元組中的值分配給變數。

#tuple packingplanets = (‘Earth’,‘Mars’,‘Jupiter’)#tuple unpackinga,b,c = planetsprint(a)print(b)print(c)Output:    Earth    Mars    Jupiter

萬能Python的秘訣:操縱資料的內建工具

集合

萬能Python的秘訣:操縱資料的內建工具

圖源:unsplash

集合是唯一的無序元素的集合。這意味著,即使資料重複一次以上,集合也只保留一次。

建立集合:

使用{ }花括號建立集合,並賦值。

#Creating setsnew_set = {1, 2, 3, 4, 4, 4, 5} #create setprint(new_set)Output:    {1, 2, 3, 4, 5}

向集合中新增元素:

使用add()函式賦值並新增元素。

#Adding elements to a Setnew_set = {1, 2, 3}new_set。add(4) #add element to setprint(new_set)Output:    {1, 2, 3, 4}

集合操作:

可以對一個集合執行的不同操作如下所示。

· union()函式合併了兩個集合中的資料。

· intersection()函式只查詢在這兩個集合中同時出現的資料。

· difference()函式刪除兩個集合中同時存在的資料,並只輸出在傳遞的集合中存在的資料。

· symmetric_difference()函式執行與difference()函式相同的操作,但是輸出在兩個集合中保留的資料。

· clear()函式清空該集合。

#Operations on setmy_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為我們有效管理、組織和訪問資料提供了多種選項,學習其基本內建資料結構是Python學習之旅非常關鍵的一環。

萬能Python的秘訣:操縱資料的內建工具