成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

整理了四十個好用到起飛的 Python 技巧!

開發(fā) 后端
在本文中,云朵君將和大家一起學(xué)習(xí) 40 個可以幫助你加快數(shù)據(jù)處理效率的的方法和技巧,希望對你有所幫助。

 

寫在前面

Python簡單易學(xué),現(xiàn)今非常流行。Python被用于各種場景,如數(shù)據(jù)科學(xué)、機器學(xué)習(xí)、web開發(fā)、腳本編制、自動化等等。

Python的簡單易學(xué)性在數(shù)據(jù)科學(xué)非常重要。盡管一些數(shù)據(jù)科學(xué)家有計算機科學(xué)背景或了解其他編程語言,但仍有許多數(shù)據(jù)科學(xué)家來自各類專業(yè),如統(tǒng)計學(xué)、數(shù)學(xué)或其他技術(shù)學(xué)科,當(dāng)他們剛進入這個行業(yè)時,可能并沒有那么多編程知識。Python語法易于理解和編寫的優(yōu)勢,使它成為一種流行于快速且易于學(xué)習(xí)的編程語言。

在本文中,云朵君將和大家一起學(xué)習(xí) 40 個可以幫助你加快數(shù)據(jù)處理效率的的方法和技巧,希望對你有所幫助。

目錄

01 列表推導(dǎo)式

02 枚舉函數(shù)

03 通過函數(shù)返回多個值

04 像在數(shù)學(xué)中一樣比較多個數(shù)字

05 將字符串轉(zhuǎn)換為字符串列表

06 For-Else 方法

07 從列表中找到n個最大/小的元素

08 函數(shù)參數(shù)以列表值傳遞

09 重復(fù)整個字符串

10 從列表中找到元素的索引

11 在同一行中打印多個元素

12 分隔大數(shù)字以易于閱讀

13 反轉(zhuǎn)列表的切片

14 "is" 和 "==" 的區(qū)別

15 在一行代碼中合并 2 個字典

16 識別字符串是否以特定字母開頭

17 獲取字符的Unicode

18 獲取字典的鍵值對

19 在數(shù)學(xué)運算中使用布爾值

20 在列表的特定位置添加值

21 過濾器filter()函數(shù)

22 創(chuàng)建沒有參數(shù)邊界的函數(shù)

23 一次迭代兩個或多個列表

24 改變句子中字母的大小寫

25 檢查對象使用的內(nèi)存大小

26 Map() 函數(shù)

27 反轉(zhuǎn)整個字符串

28 代碼塊的執(zhí)行時間

29 刪除字符串的左側(cè)或右側(cè)字符

30 在元組或列表中查找元素的索引

31 清空列表或集合中元素

32 連接兩個集合

33 根據(jù)頻率對列表的值排序

34 從列表中刪除重復(fù)值

35 列表中元素連接為句子

36 一次從函數(shù)返回多個值

37 找出兩個列表之間的差異

38 將兩個列表合并為一個字典

39 執(zhí)行字符串表示的代碼

40 字符串格式化

01 列表推導(dǎo)式

列表的元素可以在一行中循環(huán)遍歷。 

  1. numbers = [1, 2, 3, 4, 5, 6, 7, 8]  
  2. even_numbers = [number for number in numbers if number % 2 == 0]  
  3. print(even_numbers)  

輸出

[1,3,5,7]

同樣可以使用字典、集合和生成器來完成推導(dǎo)式。 

  1. dictionary = {'first_num': 1, 'second_num': 2,  
  2.               'third_num': 3, 'fourth_num': 4}  
  3. oddvalues = {key: value for (key, value) in dictionary.items() if value % 2 != 0}  
  4. print(oddvalues)Output: {'first_num': 1,   
  5.                          'third_num': 3} 

02 枚舉函數(shù)

Enumerate (枚舉) 是一個很有用的函數(shù),用于迭代對象,如列表、字典或文件。該函數(shù)生成一個元組,其中包括通過對象迭代獲得的值以及循環(huán)計數(shù)器(從 0 的起始位置)。當(dāng)希望根據(jù)索引編寫代碼時,循環(huán)計數(shù)器就派上用場了。

來看一個示例,其中第一個和最后一個元素會被區(qū)別對待。 

  1. sentence = 'Just do It'  
  2. lenlength = len(sentence)  
  3. for index, element in enumerate(sentence):  
  4.     print('{}: {}'.format(index, element))  
  5.     if index == 0:  
  6.         print('The first element!')  
  7.     elif index == length - 1:  
  8.         print('The last element!') 

輸出

0: J

The first element!

1: u

2: s

3: t

4:

5: d

6: o

7:

8: I

9: t

The last element!

也可以使用 enumerate 函數(shù)枚舉文件。在下面的示例中,在跳出循環(huán)之前打印 CSV 文件的前 10 行。并且可以在任何文件上使用該函數(shù)。 

  1. with open('heart.csv') as f:  
  2.     for i, line in enumerate(f):  
  3.         if i == 10:  
  4.             break  
  5.         print(line) 

03 通過函數(shù)返回多個值

在設(shè)計函數(shù)時,我們經(jīng)常希望返回多個值。在這里介紹兩種典型的方法。

方法一

最簡單的是返回一個元組。這種方法通常只在有兩個或三個值要返回時使用。但當(dāng)元組中有更多值時,很容易忘記項目的順序。

下面的代碼部分是一個示例函數(shù),它根據(jù)學(xué)生的 ID 號將學(xué)生的名字和姓氏作為元組返回。 

  1. # 返回元組  
  2. def get_student(id_num):  
  3.     if id_num == 0:  
  4.         return '君', '云朵'  
  5.     elif id_num == 1:  
  6.         return '猴子', '小'  
  7.     else:  
  8.         raise Exception('沒有學(xué)生的id是: {}'.format(id_num)) 

當(dāng)我們使用數(shù)字 0 調(diào)用函數(shù)時,我們注意到它返回一個具有兩個值的元組:'Taha' 和 'Nate' 。 

  1. Student = get_student(0)  
  2. print('名字: {}, 姓氏: {}'.format(Student[0],   
  3.        Student[1])) 

輸出

名字:君,姓氏:云朵

方法二

第二個選擇是返回字典。因為字典是鍵值對,我們可以對返回的值進行命名,這比元組更直觀。

方法二的實現(xiàn)方式和方法一一樣,只是返回一個字典。 

  1. # 返回字典  
  2. def get_data(id_num):  
  3.     if id_num == 0:  
  4.         return {'first_name': '君',  
  5.                 'last_name': '云朵',   
  6.                 'title': '數(shù)據(jù)STUDIO', 
  7.                 'department': 'A',   
  8.                 'date_joined': '20201001'}  
  9.     elif id_num == 1:  
  10.         return {'first_name': '猴子',   
  11.                 'last_name': '小',   
  12.                 'title': '機器學(xué)習(xí)研習(xí)院',  
  13.                 'department': 'B',   
  14.                 'date_joined': '20201019'}  
  15.     else:  
  16.         raise Exception('沒有員工的id是: {}'.format(id_num)) 

當(dāng)結(jié)果是字典時,通過鍵引用特定值會更容易。我們正在調(diào)用 id_num = 0 的函數(shù)。 

  1. employee = get_data(0)  
  2. print('first_name: {}, nlast_name: {}, ntitle: {}, ndepartment: {}, ndate_joined: {}'.format(  
  3.       employee['first_name'], employee['last_name'],   
  4.     employee['title'], employee['department'],   
  5.     employee['date_joined'])) 

輸出 

  1. first_name: 君,    
  2. last_name: 云朵,    
  3. title: 數(shù)據(jù)STUDIO,    
  4. department: A,    
  5. date_joined: 20201001 

04 像在數(shù)學(xué)中一樣比較多個數(shù)字

如果有一個值并希望將其與其他兩個值進行比較,可以使用以下基本數(shù)學(xué)表達式: 1<x<30

這就是我們在小學(xué)學(xué)到的代數(shù)表達式。同樣的語句也可以在 Python 中使用。你應(yīng)該用過如下的比較方式:

1<x and x<30

在 Python 中實現(xiàn)上述比較方式的另一種比較方法是:1<x<30 

  1. x = 5  
  2. print(1<x<30 

輸出

True

05 將字符串轉(zhuǎn)換為字符串列表

假設(shè)將函數(shù)的輸入作為字符串,但它應(yīng)該是這樣的列表: 

  1. 輸入 = [[1, 2, 3], [4, 5, 6]] 

其實無需處理復(fù)雜的正則表達式,只需導(dǎo)入模塊'ast'并調(diào)用其函數(shù)literal_eval: 

  1. import ast  
  2. def string_to_list(string):  
  3.     return ast.literal_eval(string)  
  4. string = "[[1, 2, 3],[4, 5, 6]]"  
  5. my_list = string_to_list(string)  
  6. print(my_list) 

輸出

[[1, 2, 3], [4, 5, 6]]

06 For-Else 方法

此方法用于在列表上應(yīng)用循環(huán)。通常,當(dāng)你想遍歷你應(yīng)用的列表時,可以使用 for 循環(huán)。但是在這種方法中,你可以在循環(huán)中傳遞一個 else 條件,這種情況極為罕見。其他編程語言不支持這種方法。

看看它在一般情況下是如何工作的:如果要檢查列表中是否有偶數(shù)。 

  1. number_List = [1, 3, 7, 9,8]  
  2. for number in number_List:  
  3.     if number % 2 == 0:  
  4.         print(number)  
  5.         break  
  6.     else:  
  7.     print("No even numbers!!") 

輸出

8

如果找到偶數(shù),則將打印該數(shù)字,并且 else 部分將不會執(zhí)行,因為我們傳遞了一個 break 語句。如果 break 語句從不執(zhí)行,則 else 塊將執(zhí)行。

07 從列表中找到N個最大/小的元素

通過使用'heapq'模塊,你可以從列表中找到 n-largest 或 n-smallest 元素。 

  1. import heapq  
  2. numbers = [80, 25, 68, 77, 95, 88, 30, 55, 40, 50]  
  3. print(heapq.nlargest(5, numbers))  
  4. print(heapq.nsmallest(5, numbers)) 

輸出

[95, 88, 80, 77, 68] [25, 30, 40, 50, 55]

08 函數(shù)參數(shù)以列表值傳遞

可以使用'*'訪問列表的所有元素。 

  1. def Summation(*arg):  
  2.     sum = 0  
  3.     for i in arg:  
  4.         sum += i  
  5.     return sum  
  6. result = Summation(*[8,5,10,7])  
  7. print(result) 

輸出

30

09 重復(fù)整個字符串

只需將字符串乘以一個數(shù)字,即希望字符串重復(fù)的次數(shù)。 

  1. value = "數(shù)據(jù)STUDIO"  
  2. print(value * 3)   
  3. print("-" *31) 

輸出

數(shù)據(jù)STUDIO數(shù)據(jù)STUDIO數(shù)據(jù)STUDIO  

----------------------------

10 從列表中找到元素的索引

使用".index"從列表中查找元素的索引。 

  1. cities= ['Vienna', 'Amsterdam', 'Paris', 'Berlin']  
  2. print(cities.index('Berlin'))  

輸出

3

11 在同一行中打印多個元素 

  1. print("數(shù)據(jù)", end="" 
  2. print("STUDIO")  
  3. print("數(shù)據(jù)", end=" " 
  4. print("STUDIO")  
  5. print('Data', 'science', 'Machine',   
  6.       'Learning', sep=', '

輸出

數(shù)據(jù)STUDIO  

數(shù)據(jù) STUDIO  

Data, science, Machine, Learning

12 分隔大數(shù)字以易于閱讀

有時,當(dāng)你嘗試打印一個大數(shù)字時,傳遞整個數(shù)字會非常混亂且難以閱讀。然而你可以使用下劃線,使其易于閱讀,打印結(jié)果并不會顯示下劃線。 

  1. print(5_000_000_000_000)  
  2. print(7_543_291_635) 

輸出

5000000000000  

7543291635

13 反轉(zhuǎn)列表的切片

當(dāng)你對列表進行切片時,你需要傳遞最小、最大和步長。要以相反的順序進行切片,你只需要傳遞一個負步長。 

  1. sentence = "數(shù)據(jù)STUDIO 云朵君"  
  2. print(sentence[21:0:-1])  
  3. # 向前走兩步  
  4. print(sentence[21:0:-2]) 

輸出

君朵云 OIDUTS據(jù)

君云ODT據(jù)

14 "is" 和 "==" 的區(qū)別

如果要檢查兩個變量是否指向同一個對象,則需要使用'is'。但是如果要檢查兩個變量是否相同,則需要使用'=='。 

  1. list1 = [7, 9, 4]  
  2. list2 = [7, 9, 4]  
  3. print(list1 == list2)   
  4. print(list1 is list2)  
  5. list3 = list1  
  6. print(list3 is list1) 

輸出

True  

False  

True

第一個語句是 True,因為 list1 和 list2 都持有相同的值,所以它們是相等的。第二個語句為 False,因為值指向內(nèi)存中的不同變量,第三個語句為 True,因為 list1 和 list3 都指向內(nèi)存中的公共對象。

15 在一行代碼中合并 2 個字典 

  1. first_dct = {"London": 1, "Paris": 2}  
  2. second_dct = {"Tokyo": 3, "Seol": 4}  
  3. merged = {**first_dct, **second_dct} 
  4. print(merged) 

輸出

{‘London’: 1, ‘Paris’: 2, ‘Tokyo’: 3, ‘Seol’: 4}

16 識別字符串是否以特定字母開頭

如果你需要知道字符串是否以特定字母開頭,那么你可以使用常見的索引方法。但是你也可以使用一個名為 'startswith' 的函數(shù),它會告訴你一個字符串是否以特定的單詞開頭。 

  1. sentence = "Data Studio"  
  2. print(sentence.startswith("d"))  
  3. print(sentence.startswith("o")) 

輸出

False

True

17 獲取字符的Unicode

如果你需要知道一個字符的 Unicode,那么你需要使用一個名為'ord'的函數(shù),并在函數(shù)中傳遞你想知道其 Unicode 的字符。 

  1. print(ord("T"))  
  2. print(ord("A"))   
  3. print(ord("h"))   
  4. print(ord("a")) 

輸出

84  

65  

104  

97

18 獲取字典的鍵值對

如果你想以不同的方式訪問字典的鍵和值,你可以使用名為'items()'的函數(shù)來實現(xiàn)。 

  1. cities = {'London': 1, 'Paris': 2, 'Tokyo': 3, 'Seol': 4}  
  2. for key, value in cities.items():  
  3.     print(f"Key: {key} and Value: {value}") 

輸出

Key: London and Value: 1  

Key: Paris and Value: 2  

Key: Tokyo and Value: 3  

Key: Seol and Value: 4

19 在數(shù)學(xué)運算中使用布爾值

False被視為 0,True被視為 1 

  1. x = 9  
  2. y = 3  
  3. outcome = (x - False)/(y * True)  
  4. print(outcome) 

輸出

3.0

20 在列表的特定位置添加值

如果你想使用'append' 功能向列表添加值,但它會在列表的最后位置添加一個值。如果你想在列表的特定位置添加值怎么辦?你可以使用名為 'insert' 的函數(shù)在列表的特定位置插入值。

語法 

  1. list_name.insert(position, value)  
  2. cities = ["London", "Vienna", "Rome"]  
  3. cities.append("Seoul")  
  4. print("After append:", cities)  
  5. cities.insert(0, "Berlin")  
  6. print("After insert:", cities) 

輸出

After append: ['London', 'Vienna', 

               'Rome', 'Seoul']   

After insert: ['Berlin', 'London', 

               'Vienna', 'Rome', 'Seoul']

21 過濾器 filter() 函數(shù)

過濾器filter()函數(shù)的工作顧名思義。它通過內(nèi)部傳遞的特定函數(shù)來過濾特定的迭代器。并返回一個迭代器。

語法 

  1. filter(function, iterator)  
  2. mixed_number = [8, 15, 25, 30,34,67,90,5,12]  
  3. filterfiltered_value = filter(lambda x: x > 20, mixed_number)  
  4. print(f"Before filter: {mixed_number}")  
  5. print(f"After filter: {list(filtered_value)}") 

輸出

Before filter:[8, 15, 25, 30, 34, 67, 90, 5, 12] 

After filter:[25, 30, 34, 67, 90]

22 創(chuàng)建沒有參數(shù)邊界的函數(shù)

你可以無需在意參數(shù)而創(chuàng)建一個函數(shù)。可以在調(diào)用函數(shù)時傳遞任意數(shù)量的參數(shù)。 

  1. def multiplication(*arguments):  
  2.     mul = 1  
  3.     for i in arguments:  
  4.         mulmul = mul * i  
  5.     return mul  
  6. print(multiplication(3, 4, 5))  
  7. print(multiplication(5, 8, 10, 3))  
  8. print(multiplication(8, 6, 15, 20, 5)) 

輸出

60  

1200  

72000

23 一次迭代兩個或多個列表

你可以使用 enumerate 函數(shù)迭代單個列表,但是當(dāng)你有兩個或多個列表時,你也可以使用'zip()'函數(shù)迭代它們。 

  1. capital = ['Vienna', 'Paris', 'Seoul',"Rome"]  
  2. countries = ['澳大利亞', '法國', '韓國',"意大利"]  
  3. for cap, country in zip(capital, countries):  
  4.     print(f"{cap} 是 {country} 的首都") 

輸出

Vienna 是 澳大利亞 的首都  

Paris 是 法國 的首都  

Seoul 是 韓國 的首都  

Amsterdam 是 意大利 的首都

24 改變句子中字母的大小寫

如果你想改變字母的大小寫,即大寫到小寫,小寫到大寫,那么你可以使用一個叫做'swapcase'的函數(shù)實現(xiàn)這一功能。 

  1. sentence = "Data STUDIO"  
  2. changed_sen = sentence.swapcase()  
  3. print(changed_sen) 

輸出

dATA studio

25 檢查對象使用的內(nèi)存大小

要檢查對象使用的內(nèi)存,首先導(dǎo)入 'sys' 庫,然后使用該庫中名為 'getsizeof' 的方法。它將返回對象使用的內(nèi)存大小。 

  1. import sys 
  2. mul = 5*6  
  3. print(sys.getsizeof(mul)) 

輸出

28

26 Map() 函數(shù)

'Map()' 函數(shù)用于特定的功能應(yīng)用到一個給定的迭代器。

語法

map(function, iterator) 

  1. values_list = [8, 10, 6, 50]  
  2. quotient = map(lambda x: x/2, values_list)  
  3. print(f"Before division: {values_list}")  
  4. print(f"After division: {list(quotient)}") 

輸出

Before division:[8, 10, 6, 50]   

After division:[4.0, 5.0, 3.0, 25.0]

27 反轉(zhuǎn)整個字符串

要反轉(zhuǎn)字符串,你可以使用切片方法。 

  1. value = "OIDUTS ataD"  
  2. print("Reverse is:", value[::-1]) 

輸出

Reverse is: Data STUDIO

28 代碼塊的執(zhí)行時間

當(dāng)你訓(xùn)練機器學(xué)習(xí)或深度學(xué)習(xí)模型,或者只是運行一個代碼塊時,獲取需要檢查運行代碼塊花費了多少時間。你可以選擇在代碼塊的頂部使用一個魔法函數(shù)'%%time'。它將顯示運行代碼塊所花費的時間。 

  1. %%time  
  2. sentence = " Data STUDIO."  
  3. changed_sen = sentence.swapcase()  
  4. print(changed_sen)  

輸出

  dATA studio.  

 CPU times: user 145 µs, sys: 578 µs, 

 total: 723 µs  

 Wall time: 1.04 ms

29 刪除字符串的左側(cè)或右側(cè)字符

有兩個函數(shù)稱為 'rstrip()' 和 'lstrip()','rstrip()' 用于從字符串右側(cè)刪除某個字符,而 'lstrip()' 用于從字符串左側(cè)刪除某個字符。兩個函數(shù)的默認值都是空格。但是你可以傳遞你的特定字符以將它們從字符串中刪除。 

  1. sentence1 = "Data STUDIO     "  
  2. print(f"After removing the right space: {sentence1.rstrip()}")   
  3. sentence2 = "        Data STUDIO"  
  4. print(f"After removing the left space: {sentence2.lstrip()}")  
  5. sentence3 = "Data STUDIO .,bbblllg"  
  6. print("After applying rstrip:", sentence3.rstrip(".,blg")) 

輸出 

  1. After removing the right space: Data STUDIO    
  2. After removing the left space: Data STUDIO    
  3. After applying rstrip: Data STUDIO  
  4. 你可以通過在其中運行 for 循環(huán)來計算元素在列表中出現(xiàn)的次數(shù)。但是你可以更輕松地做到這一點,只需調(diào)用名為'count'的列表中的方法即可。  
  5. cities= ["Amsterdam", "Berlin", "New York",   
  6.          "Seoul", "Tokyo", "Paris", "Paris", 
  7.          "Vienna","Paris"] 
  8. print("Paris appears", cities.count("Paris"), "times in the list") 

輸出

Paris appears 3 times in the list

30 在元組或列表中查找元素的索引

只需在該元組或列表上調(diào)用一個名為'index'的簡單方法,就可以在該元組或列表中找到元素的索引。 

  1. cities_tuple = ("Berlin", "Paris", 5, "Vienna", 10)  
  2. print(cities_tuple.index("Paris"))   
  3. cities_list = ['Vienna', 'Paris', 'Seoul',"Amsterdam"]  
  4. print(cities_list.index("Amsterdam")) 

輸出

1  

3

31 清空列表或集合中元素

可以通過在列表或集合上應(yīng)用稱為'clear'的方法從列表或集合中刪除所有元素。 

  1. cities_list = ['Vienna', 'Paris', 'Seoul',"Amsterdam"]  
  2. print(f"Before removing from the list: {cities_list}")  
  3. cities_list.clear()  
  4. print(f"After removing from the list: {cities_list}")  
  5. cities_set = {'Vienna', 'Paris', 'Seoul',"Amsterdam"}  
  6. print(f"Before removing from the set: {cities_set}")  
  7. cities_set.clear() 
  8. print(f"After removing from the set: {cities_set}") 

輸出

Before removing from the list: ['Vienna', 

              'Paris', 'Seoul', 'Amsterdam']  

After removing from the list: []  

Before removing from the set: {'Seoul', 

              'Amsterdam', 'Paris', 'Vienna'}  

After removing from the set: set()

32 連接兩個集合

要加入兩個集合,你可以應(yīng)用稱為union()的方法。它將加入你應(yīng)用該方法的兩個列表。 

  1. set1 = {'Vienna', 'Paris', 'Seoul'}  
  2. set2 = {"Tokyo", "Rome",'Amsterdam'}  
  3. print(set1.union(set2)) 

輸出

{'Seoul', 'Rome', 'Paris', 

 'Amsterdam', 'Tokyo', 'Vienna'}

33 根據(jù)頻率對列表的值排序

首先,使用名為 collections 的模塊中的'counter'來測量每個值的頻率,然后對計數(shù)器的結(jié)果應(yīng)用名為'most_common'的方法,根據(jù)頻率對列表中的值進行排序。 

  1. from collections import Counter  
  2. count = Counter([7, 6, 5, 6, 8, 6, 6, 6])  
  3. print(count)  
  4. print("根據(jù)頻率對值進行排序:", count.most_common()) 

輸出:

Counter({6: 5, 7: 1, 5: 1, 8: 1})  

根據(jù)頻率對值進行排序:[(6, 5), (7, 1), (5, 1), (8, 1)]

34 從列表中刪除重復(fù)值

首先將列表轉(zhuǎn)換為集合,這將刪除重復(fù)值,因為集合不包含重復(fù)值。然后再次將集合轉(zhuǎn)換為列表,這樣就可以輕松地從列表中刪除重復(fù)的值。 

  1. cities_list = ['Vienna', 'Paris', 'Seoul',  
  2.                "Amsterdam","Paris","Amsterdam", "Paris"]  
  3. cities_list = set(cities_list)  
  4. print("從列表中刪除重復(fù)值后:", list(cities_list)) 

輸出

從列表中刪除重復(fù)值后:['Vienna', 'Amsterdam', 

                   'Seoul', 'Paris']

35 列表中元素連接為句子

通過使用稱為'join'的方法,可以連接列表的所有單個元素并生成單個字符串或句子。 

  1. words_list = ["數(shù)據(jù)", "STUDIO", "云朵君"]  
  2. print(" ".join(words_list)) 

輸出

數(shù)據(jù)STUDIO云朵君

36 一次從函數(shù)返回多個值

可以在 python 中做到一次從一個函數(shù)返回多個值。 

  1. def calculation(number):  
  2.     mul = number*2  
  3.     div = number/2  
  4.     summation = number+2  
  5.     subtract = number-2  
  6.     return mul, div, summation, subtract  
  7. mul, div, summation, subtract = calculation(10) 
  8.  print("乘法:", mul) 
  9. print("除法:", div)  
  10. print("加法:", summation)  
  11. print("減法:", subtract) 

輸出

乘法: 20  

除法: 5.0   

加法: 12  

減法: 8

37 找出兩個列表之間的差異

首先,將列表轉(zhuǎn)換為集合,然后對這些集合應(yīng)用稱為'symmetric_difference'的方法。這將返回這兩個列表之間的差異。 

  1. cities_list1 = ['Vienna', 'Paris', 'Seoul',"Amsterdam", "Berlin", "London"]  
  2. cities_list2 = ['Vienna', 'Paris', 'Seoul',"Amsterdam"]  
  3. cities_set1 = set(cities_list1)  
  4. cities_set2 = set(cities_list2)  
  5. difference = list(cities_set1.symmetric_difference(cities_set2))  
  6. print(difference) 

輸出

['Berlin', 'London']

38 將兩個列表合并為一個字典

首先,在這兩個列表上應(yīng)用 zip 函數(shù),然后將 zip 函數(shù)的輸出轉(zhuǎn)換為字典。你的工作已完成,將兩個列表轉(zhuǎn)換為一個字典就是這么容易。 

  1. number = [1, 2, 3]  
  2. cities = ['維也納', '巴黎', '首爾']  
  3. result = dict(zip(number, cities))  
  4. print(result) 

輸出

{1:'維也納', 2:'巴黎', 3:'首爾'}

39 執(zhí)行字符串表示的代碼

將字符串編譯成python能識別或可執(zhí)行的代碼,也可以將文字讀成字符串再編譯。 

  1. s  = "print('helloworld')"  
  2. r = compile(s,"<string>", "exec")  
  3. exec(r) 

輸出

helloworld

40 字符串格式化

格式化輸出字符串,format(value, format_spec)實質(zhì)上是調(diào)用了value的format(format_spec)方法。 

  1. print("i am {0},age{1}".format("tom",18))  

輸出

i am tom,age18

3.1415926 {:.2f} 3.14 保留小數(shù)點后兩位
3.1415926 {:+.2f} 3.14 帶符號保留小數(shù)點后兩位
-1 {:+.2f} -1 帶符號保留小數(shù)點后兩位
2.71828 {:.0f} 3 不帶小數(shù)
5 {:0>2d} 5 數(shù)字補零 (填充左邊, 寬度為2)
5 {:x<4d} 5xxx 數(shù)字補x (填充右邊, 寬度為4)
10 {:x<4d} 10xx 數(shù)字補x (填充右邊, 寬度為4)
1000000 {:,} 1,000,000 以逗號分隔的數(shù)字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00E+09 指數(shù)記法
18 {:>10d} ' 18' 右對齊 (默認, 寬度為10)
18 {:<10d} '18 ' 左對齊 (寬度為10)
18 {:^10d} ' 18 ' 中間對齊 (寬度為10)

 

 

責(zé)任編輯:龐桂玉 來源: Python編程
相關(guān)推薦

2021-10-06 15:58:26

Python工具代碼

2021-07-19 15:47:45

Python編程語言代碼

2023-04-26 00:34:36

Python技巧程序員

2021-11-15 10:02:16

Python命令技巧

2022-08-26 09:38:39

Pandas數(shù)據(jù)查詢

2024-02-22 17:09:53

業(yè)務(wù)分析模型

2024-08-13 12:03:09

業(yè)務(wù)分析模型

2021-12-11 23:13:16

Python語言技巧

2022-09-16 09:41:23

Python函數(shù)代碼

2022-06-24 10:16:59

Python精選庫

2024-12-03 14:33:42

Python遞歸編程

2019-10-18 10:04:45

Vim文本編輯器語言

2017-08-16 17:00:19

2021-08-13 22:35:57

Windows微軟電腦

2022-08-25 14:24:17

Python技巧

2022-05-12 08:12:51

PythonPip技巧

2019-08-22 17:43:40

PythonHTML可視化技術(shù)

2022-03-10 08:44:50

Python開發(fā)工具

2020-08-04 11:03:50

Python內(nèi)置異常開發(fā)

2022-08-22 09:39:25

Python人工智能庫
點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 欧美专区在线 | 久久国产精品一区二区三区 | 色婷婷综合久久久久中文一区二区 | 午夜免费福利片 | 日韩av大片免费看 | 国产目拍亚洲精品99久久精品 | 久久这里只有精品首页 | av网站在线看 | 1级毛片 | 99亚洲| 国产综合精品 | 俺去俺来也www色官网cms | 免费a级毛片在线播放 | 亚洲一区中文字幕在线观看 | 精品三级在线观看 | 三级在线观看 | 久久亚洲欧美日韩精品专区 | 精品在线播放 | 91免费看片| 久久com| 欧美高清dvd | 日韩午夜精品 | 91精品国产综合久久国产大片 | 一区二区三区中文字幕 | 欧美一级高潮片免费的 | 日韩欧美一区二区三区免费观看 | 成人小视频在线观看 | 国产一区二区电影 | 亚洲综合大片69999 | 日韩电影一区二区三区 | 国产一区二区三区免费观看视频 | 91在线视频免费观看 | 久草视频在线播放 | 日本大香伊一区二区三区 | 一区二区免费视频 | 国产精品久久一区二区三区 | 99福利视频导航 | 国产视频h | 国产不卡在线 | 国产精品美女在线观看 | 亚洲国内精品 |