日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網營銷解決方案
萬能Python的秘訣:操縱數據的內置工具

本文轉載自公眾號“讀芯術”(ID:AI_Discovery)。

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

Python的萬能之處正在于其內置的數據結構,它使編碼變得簡單,不受數據類型限制,并可以根據需要操縱數據。

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

  • 列表
  • 字典
  • 元組
  • 集合

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

1. 列表

Python列表是按順序排列的任意類型的項的集合。一個列表可以有重復的項,因為每個項都是使用索引訪問的,而且可以通過使用負索引逆向訪問該列項。列表是可變的,這意味著即使在創(chuàng)建了項之后,也可以添加、刪除或更改項;一個列表中還可以包含另一個列表。

(1) 創(chuàng)建列表:

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

 
 
 
 
  1. #Creating a list fruits = ['Apple', 'Banana', "Orange"] 
  2. print(type(fruits)) #returns type 
  3. print(fruits) #prints the elements of the listOutput: 
  4.      
  5.     ['Apple', 'Banana', 'Orange'] 

(2) 訪問列表:

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

 
 
 
 
  1. #Access elements in the fruits listfruits = ['Apple', 'Banana',"Orange"] 
  2. print(fruits[0]) #index 0 is the first element 
  3. print(fruits[1]) 
  4. print(fruits[2])Output: 
  5.     Apple 
  6.     Banana 
  7.     Orange 

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

 
 
 
 
  1. #Access elements in the fruits list using negative indexesfruits = ['Apple','Banana', "Orange"] 
  2. print(fruits[-1]) #index -1 is the last element 
  3. print(fruits[-2]) 
  4. print(fruits[-3])Output: 
  5.     Orange 
  6.     Banana 
  7.     Apple 

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

 
 
 
 
  1. #Accessing range of elements using slicingfruits = ['Apple', 'Banana',"Orange"] 
  2.  
  3. fruits #all elements  
  4. ['Apple', 'Guava', 'Banana', 'Kiwi'] #output 
  5.  
  6. fruits[::1] #start to end with step 1 
  7. ['Apple', 'Guava', 'Banana', 'Kiwi'] #outputfruits[::2] #start to endwith step 2 basically index 0 & 2 
  8. ['Apple', 'Banana'] #output 
  9.  
  10. fruits[::3] #start to end with step 2 basically index 0 & 3 
  11. ['Apple', 'Kiwi'] #output 
  12.  
  13. fruits[::-1] #start to end with step 2 - reverse order 
  14. ['Kiwi', 'Banana', 'Guava', 'Apple'] #output 

(3) 向列表中添加元素:

可以使用append()、extend()和insert()函數向列表添加項。

 
 
 
 
  1. #Adding elementsfruits = ['Apple', 'Banana', "Orange"]#Appendnew elements 
  2. fruits.append('Kiwi') 
  3. print(fruits) 
  4.  
  5. Output:  
  6.     ['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 
  7. print(fruits) 
  8.  
  9. Output:  
  10.     ['Apple', 'Guava', 'Banana','Orange', 'Kiwi']  

(4) 從列表中刪除項:

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

  • del()函數刪除給定索引處的元素。
  • pop()函數從列表中刪除給定索引處的元素,也可以將刪除的元素賦值給變量。如果未指定索引值,則刪除列表中的最后一個元素。
  • remove()函數根據元素的值來刪除元素。
  • clear()函數清空列表。
 
 
 
 
  1. #Deleting elements from the listfruits = ['Apple', 'Guava', 'Banana','Orange', 'Kiwi'] 
  2.  
  3. #del() function 
  4. del fruits[3] #delete element at index 4 
  5. print(fruits) 
  6.  
  7. Output:  
  8.     ['Apple', 'Guava', 'Banana', 'Kiwi']#pop()function 
  9. del_fruit = fruits.pop(2) 
  10. print(del_fruit) 
  11. print(fruits) 
  12.  
  13. Output:  
  14.     'Banana'   
  15.     ['Apple', 'Guava', 'Orange', 'Kiwi'] 
  16.  
  17. #Remove function 
  18. fruits.remove('Apple') 
  19. print(fruits) 
  20.  
  21. Output:  
  22.     ['Guava', 'Banana', 'Orange', 'Kiwi'] 
  23.      
  24. #Clear() function 
  25. fruits.clear() 
  26. print(fruits) 
  27.  
  28. Output :  
  29.     [] # clears the list 

其他函數:

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

  • len()函數返回列表的長度。
  • index()函數查找第一次遇到的傳入值的索引值。
  • count()函數查找傳遞給它的值的個數。
  • sorted()和sort()函數用于對列表的值進行排序。sorted()具有返回類型,而sort()修改原始列表。
 
 
 
 
  1. #Other functions for listnum_list = [1, 2, 3, 10, 20, 10] 
  2. print(len(num_list)) #find length of list 
  3. print(num_list.index(10)) #find index of element that occurs first 
  4. print(num_list.count(10)) #find count of the element 
  5. print(sorted(num_list)) #print sorted list but not change original 
  6. num_list.sort(reverse=True) #sort original list 
  7. print(num_list)Output: 
  8. [1, 2, 3, 10, 10, 20] 
  9. [20, 10, 10, 3, 2, 1] 

2. 字典

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

圖源:unsplash

(1) 創(chuàng)建字典:

字典由冒號分隔的{}大括號或使用dict()函數編寫鍵和值被創(chuàng)建。

 
 
 
 
  1. #Creating Dictionariesnew_dict = {} #empty dictionary 
  2. print(new_dict) 
  3.  
  4. new_dict = {1: 'Python', 2: 'Java'} #dictionary with elements 
  5. print(new_dict)Output: 
  6.     {} 
  7.     {1: 'Python', 2: 'Java'} 

(2) 改變并增加鍵值對:

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

 
 
 
 
  1. #Changing and Adding key, value pairslang_dict = {'First': 'Python','Second': 'Java'} 
  2. print(lang_dict) 
  3.  
  4. lang_dict['Second'] = 'C++' #changing element 
  5. print(lang_dict) 
  6.  
  7. lang_dict['Third'] = 'Ruby' #adding key-value pair 
  8. print(lang_dict)Output: 
  9.     {'First': 'Python', 'Second': 'Java'} 
  10.     {'First': 'Python', 'Second': 'C++'} 
  11.     {'First': 'Python', 'Second': 'C++','Third': 'Ruby'} 

(3) 訪問字典中的元素:

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

 
 
 
 
  1. #Accessing Elementslang_dict = {'First': 'Python', 'Second': 'Java'} 
  2. print(lang_dict['First']) #access elements using keys 
  3. print(lang_dict.get('Second'))Output: 
  4.     Python 
  5.     Java 

(4) 刪除字典中的鍵值對:

這些是字典中用于刪除元素的函數。

  • pop()-刪除值并返回已刪除的值
  • popitem()-獲取鍵值對并返回鍵和值的元組
  • clear()-清除整個字典
 
 
 
 
  1. #Deleting key, value pairs in a dictionarylang_dict = {'First': 'Python','Second': 'Java', 'Third': 'Ruby'} 
  2. a = lang_dict.pop('Third') #pop element 
  3. print('Value:', a) 
  4. print('Dictionary:', lang_dict) 
  5.  
  6. b = lang_dict.popitem() #pop the key-value pair 
  7. print('Key, value pair:', b) 
  8. print('Dictionary', lang_dict) 
  9.  
  10. lang_dict.clear() #empty dictionary 
  11. print(lang_dict)Output: 
  12.     Value: Ruby #pop element 
  13.     Dictionary: {'First': 'Python','Second': 'Java'} 
  14.     Key, value pair: ('Second', 'Java') #popthe key-value pair 
  15.     Dictionary {'First': 'Python'} 
  16.     {} #empty dictionary 

(5) 其他函數:

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

 
 
 
 
  1. #Other functions for dictionarylang_dict = {'First': 'Python','Second': 'Java', 'Third': 'Ruby'} 
  2. print(lang_dict.keys()) #get keys 
  3. print(lang_dict.values()) #get values 
  4. print(lang_dict.items()) #get key-value pairs 
  5. print(lang_dict.get('First'))Output: 
  6.     dict_keys(['First', 'Second','Third']) 
  7.     dict_values(['Python', 'Java','Ruby']) 
  8.     dict_items([('First', 'Python'),('Second', 'Java'), ('Third', 'Ruby')]) 
  9.     Python 

3. 元組

圖源:unsplash

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

(1) 創(chuàng)建元組:

使用()圓括號或tuple()函數創(chuàng)建元組。

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

(2) 訪問元組中的元素:

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

 
 
 
 
  1. #access elementsmy_tuple2 = (1, 2, 3,'new') for x in my_tuple2:  
  2.     print(x) # prints all the elementsin my_tuple2print(my_tuple2) 
  3. print(my_tuple2[0]) #1st element 
  4. print(my_tuple2[:]) #all elements 
  5. print(my_tuple2[3][1]) #this returns the 2nd character of the element atindex 3  
  6. print(my_tuple2[-1]) #last elementOutput: 
  7.     1 
  8.     2 
  9.     3 
  10.     new 
  11.     (1, 2, 3, 'new') 
  12.     1 
  13.     (1, 2, 3, 'new') 
  14.     e 
  15.     new 

(3) 在另一元組中追加元素:

要追加值,可以使用'+'操作符。

 
 
 
 
  1. #Appending elementsmy_tuple = (1, 2, 3) 
  2. my_tuplemy_tuple = my_tuple + (4, 5, 6) #add elements 
  3. print(my_tuple)Output: 
  4.     (1, 2, 3, 4, 5, 6) 

(4) 元組賦值:

元組打包和解包操作很有用,執(zhí)行這些操作可以在一行中將另一個元組的元素賦值給當前元組。元組打包就是通過添加單個值來創(chuàng)建元組,元組拆包則是將元組中的值分配給變量。

 
 
 
 
  1. #tuple packing 
  2. planets = ('Earth','Mars','Jupiter') 
  3.  
  4. #tuple unpackinga,b,c = planets 
  5. print(a) 
  6. print(b) 
  7. print(c)Output: 
  8.     Earth 
  9.     Mars 
  10.     Jupiter 

4. 集合

圖源:unsplash

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

(1) 創(chuàng)建集合:

使用{ }花括號創(chuàng)建集合,并賦值。

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

(2) 向集合中添加元素:

使用add()函數賦值并添加元素。

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

(3) 集合操作:

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

  • union()函數合并了兩個集合中的數據。
  • intersection()函數只查找在這兩個集合中同時出現的數據。
  • difference()函數刪除兩個集合中同時存在的數據,并只輸出在傳遞的集合中存在的數據。
  • symmetric_difference()函數執(zhí)行與difference()函數相同的操作,但是輸出在兩個集合中保留的數據。
  • clear()函數清空該集合。
 
 
 
 
  1. #Operations on set 
  2. my_set = {1, 2, 3, 4} 
  3. my_set_2 = {3, 4, 5, 6} 
  4.  
  5. print(my_set.union(my_set_2)) 
  6. print(my_set.intersection(my_set_2)) 
  7. print(my_set.difference(my_set_2)) 
  8. print(my_set.symmetric_difference(my_set_2)) 
  9.  
  10. my_set.clear() 
  11. print(my_set)Output: 
  12.     {1, 2, 3, 4, 5, 6} 
  13.     {3, 4} 
  14.     {1, 2} 
  15.     {1, 2, 5, 6} 
  16.     set() 

Python為我們有效管理、組織和訪問數據提供了多種選項,學習其基本內置數據結構是Python學習之旅非常關鍵的一環(huán)。


當前名稱:萬能Python的秘訣:操縱數據的內置工具
新聞來源:http://www.dlmjj.cn/article/dpgohcs.html