自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

好用到哭!請記住這20段Python代碼

開發(fā) 后端
Python是一種非BS編程語言。設計簡單和易讀性是它廣受歡迎的兩大原因。正如Python的宗旨:美麗勝于丑陋,顯式勝于隱式。

好用到哭!請記住這20段Python代碼

Python是一種非BS編程語言。設計簡單和易讀性是它廣受歡迎的兩大原因。正如Python的宗旨:美麗勝于丑陋,顯式勝于隱式。

記住一些幫助提高編碼設計的常用小訣竅是有用的。在必要時刻,這些小訣竅能夠減少你上網查Stack Overflow的麻煩。而且它們會在每日編程練習中助你一臂之力。

1. 反轉字符串

以下代碼使用Python切片操作來反轉字符串。 

  1. # Reversing a string using slicing 
  2.  
  3. my_string = "ABCDE" 
  4. reversed_string = my_string[::-1] 
  5.  
  6. print(reversed_string) 
  7.  
  8. Output 
  9. # EDCBA 

2. 使用標題類(首字母大寫)

以下代碼可用于將字符串轉換為標題類。這是通過使用字符串類中的title()方法來完成。 

  1. my_string = "my name is chaitanya baweja" 
  2.  
  3. # using the title() function of string class 
  4. new_string = my_string.title() 
  5.  
  6. print(new_string) 
  7.  
  8. Output 
  9. # My Name Is Chaitanya Baweja 

3. 查找字符串的唯一要素

以下代碼可用于查找字符串中所有的唯一要素。我們使用其屬性,其中一套字符串中的所有要素都是唯一的。 

  1. my_string = "aavvccccddddeee" 
  2.  
  3. # converting the string to a set 
  4. temp_set = set(my_string) 
  5.  
  6. # stitching set into a string using join 
  7. new_string = .join(temp_set) 
  8.  
  9. print(new_string) 

4. 輸出 n次字符串或列表

你可以對字符串或列表使用乘法(*)。如此一來,可以按照需求將它們任意倍增。 

  1. n = 3 # number of repetitions 
  2.  
  3. my_string = "abcd" 
  4. my_list = [1,2,3] 
  5.  
  6. print(my_string*n) 
  7. # abcdabcdabcd 
  8.  
  9. print(my_list*n) 
  10. # [1,2,3,1,2,3,1,2,3] 
  11. import streamlit as st 

一個有趣的用例是定義一個具有恒定值的列表,假設為零。 

  1. n = 4 
  2. my_list = [0]*n # n denotes the length of the required list 
  3. # [0, 0, 0, 0] 

5. 列表解析

在其他列表的基礎上,列表解析為創(chuàng)建列表提供一種優(yōu)雅的方式。

以下代碼通過將舊列表的每個對象乘兩次,創(chuàng)建一個新的列表。 

  1. # Multiplying each element in a list by 2 
  2.  
  3. original_list = [1,2,3,4] 
  4.  
  5. new_list = [2*x for x in original_list] 
  6.  
  7. print(new_list) 
  8. # [2,4,6,8] 

6. 兩個變量之間的交換值

Python可以十分簡單地交換兩個變量間的值,無需使用第三個變量。 

  1. a = 1 
  2. b = 2 
  3.  
  4. a, b = b, a 
  5.  
  6. print(a) # 2 
  7. print(b) # 1 

7. 將字符串拆分成子字符串列表

通過使用.split()方法,可以將字符串分成子字符串列表。還可以將想拆分的分隔符作為參數(shù)傳遞。 

  1. string_1 = "My name is Chaitanya Baweja" 
  2. string_2 = "sample/ string 2" 
  3.  
  4. default separator 
  5. print(string_1.split()) 
  6. # [ My , name , is , Chaitanya , Baweja ] 
  7.  
  8. # defining separator as / 
  9. print(string_2.split( / )) 
  10. # [ sample , string 2 ] 

8. 將字符串列表整合成單個字符串

join()方法將字符串列表整合成單個字符串。在下面的例子中,使用comma分隔符將它們分開。 

  1. list_of_strings = [ My , name , is , Chaitanya , Baweja ] 
  2.  
  3. # Using join with the comma separator 
  4. print( , .join(list_of_strings)) 
  5.  
  6. Output 
  7. # My,name,is,Chaitanya,Baweja 

9. 檢查給定字符串是否是回文(Palindrome)

反轉字符串已經在上文中討論過。因此,回文成為Python中一個簡單的程序. 

  1. my_string = "abcba" 
  2.  
  3. if my_string == my_string[::-1]: 
  4.     print("palindrome"
  5. else
  6.     print("not palindrome"
  7.  
  8. Output 
  9. # palindrome 

10. 列表的要素頻率

有多種方式都可以完成這項任務,而我最喜歡用Python的Counter 類。Python計數(shù)器追蹤每個要素的頻率,Counter()反饋回一個字典,其中要素是鍵,頻率是值。

也使用most_common()功能來獲得列表中的most_frequent element。 

  1. # finding frequency of each element in a list 
  2. from collections import Counter 
  3.  
  4. my_list = [ a , a , b , b , b , c , d , d , d , d , d ] 
  5. count = Counter(my_list) # defining a counter object 
  6.  
  7. print(count) # Of all elements 
  8. # Counter({ d : 5, b : 3, a : 2, c : 1}) 
  9.  
  10. print(count[ b ]) # of individual element 
  11. # 3 
  12.  
  13. print(count.most_common(1)) # most frequent element 
  14. # [( d , 5)] 

11. 查找兩個字符串是否為anagrams

Counter類的一個有趣應用是查找anagrams。

anagrams指將不同的詞或詞語的字母重新排序而構成的新詞或新詞語。

如果兩個字符串的counter對象相等,那它們就是anagrams. 

  1. From collections import Counter 
  2.  
  3. str_1, str_2, str_3 = "acbde""abced""abcda" 
  4. cnt_1, cnt_2, cnt_3  = Counter(str_1), Counter(str_2), Counter(str_3) 
  5.  
  6. if cnt_1 == cnt_2: 
  7.     print( 1 and 2 anagram ) 
  8. if cnt_1 == cnt_3: 
  9.     print( 1 and 3 anagram ) 

12. 使用try-except-else塊

通過使用try/except塊,Python 中的錯誤處理得以輕松解決。在該塊添加else語句可能會有用。當try塊中無異常情況,則運行正常。

如果要運行某些程序,使用 finally,無需考慮異常情況。 

  1. a, b = 1,0 
  2.  
  3. try: 
  4.     print(a/b) 
  5.     # exception raised when b is 0 
  6. except ZeroDivisionError: 
  7.     print("division by zero"
  8. else
  9.     print("no exceptions raised"
  10. finally: 
  11.     print("Run this always"

13.使用列舉獲取索引和值對

以下腳本使用列舉來迭代列表中的值及其索引。 

  1. my_list = [ a ,  b ,  c ,  d ,  e ] 
  2.  
  3. for index, value in enumerate(my_list): 
  4.     print( {0}: {1} .format(index, value)) 
  5.  
  6. # 0: a 
  7. # 1: b 
  8. # 2: c 
  9. # 3: d 
  10. # 4: e 

14. 檢查對象的內存使用

以下腳本可用來檢查對象的內存使用。 

  1. import sys 
  2.  
  3. num = 21 
  4.  
  5. print(sys.getsizeof(num)) 
  6.  
  7. In Python 2, 24 
  8. In Python 3, 28 

15. 合并兩個字典

在Python 2 中,使用update()方法合并兩個字典,而Python3.5 使操作過程更簡單。

在給定腳本中,兩個字典進行合并。我們使用了第二個字典中的值,以免出現(xiàn)交叉的情況。 

  1. dict_1 = { apple : 9,  banana : 6} 
  2. dict_2 = { banana : 4, orange : 8} 
  3.  
  4. combined_dict = {**dict_1, **dict_2} 
  5.  
  6. print(combined_dict) 
  7. Output 
  8. # { apple : 9, banana : 4, orange : 8} 

16. 執(zhí)行一段代碼所需時間

下面的代碼使用time 軟件庫計算執(zhí)行一段代碼所花費的時間。 

  1. import time 
  2.  
  3. start_time = time.time() 
  4. # Code to check follows 
  5. a, b = 1,2 
  6. c = a+ b 
  7. # Code to check ends 
  8. end_time = time.time() 
  9. time_taken_in_micro = (end_time- start_time)*(10**6) 
  10.  
  11. print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro) 

17. 列表清單扁平化

有時你不確定列表的嵌套深度,而且只想全部要素在單個平面列表中。

可以通過以下方式獲得: 

  1. from iteration_utilities import deepflatten 
  2.  
  3. # if you only have one depth nested_list, use this 
  4. def flatten(l): 
  5.   return [item for sublist in l for item in sublist] 
  6.  
  7. l = [[1,2,3],[3]] 
  8. print(flatten(l)) 
  9. # [1, 2, 3, 3] 
  10.  
  11. # if you don t know how deep the list is nested 
  12. l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]] 
  13.  
  14. print(list(deepflatten(l, depth=3))) 
  15. # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

若有正確格式化的數(shù)組,Numpy扁平化是更佳選擇。

18. 列表取樣

通過使用random軟件庫,以下代碼從給定的列表中生成了n個隨機樣本。 

  1. import random 
  2.  
  3. my_list = [ a , b , c , d , e ] 
  4. num_samples = 2 
  5.  
  6. samples = random.sample(my_list,num_samples) 
  7. print(samples) 
  8. # [ a , e ] this will have any 2 random values 

強烈推薦使用secrets軟件庫生成用于加密的隨機樣本。

以下代碼僅限用于Python 3。 

  1. import secrets                              # imports secure module. 
  2. secure_random = secrets.SystemRandom()      # creates a secure random object. 
  3.  
  4. my_list = [ a , b , c , d , e ] 
  5. num_samples = 2 
  6.  
  7. samples = secure_random.sample(my_list, num_samples) 
  8.  
  9. print(samples) 
  10. # [ e , d ] this will have any 2 random values 

19. 數(shù)字化

以下代碼將一個整數(shù)轉換為數(shù)字列表。 

  1. num = 123456 
  2.  
  3. # using map 
  4. list_of_digits = list(map(int, str(num))) 
  5.  
  6. print(list_of_digits) 
  7. # [1, 2, 3, 4, 5, 6] 
  8.  
  9. # using list comprehension 
  10. list_of_digits = [int(x) for x in str(num)] 
  11.  
  12. print(list_of_digits) 
  13. # [1, 2, 3, 4, 5, 6] 

20. 檢查唯一性

以下函數(shù)將檢查一個列表中的所有要素是否唯一。 

  1. def unique(l): 
  2.     if len(l)==len(set(l)): 
  3.         print("All elements are unique"
  4.     else
  5.         print("List has duplicates"
  6.  
  7. unique([1,2,3,4]) 
  8. All elements are unique 
  9.  
  10. unique([1,1,2,3]) 
  11. # List has duplicates 

 

責任編輯:龐桂玉 來源: 機器學習算法與Python學習
相關推薦

2019-08-22 17:43:40

PythonHTML可視化技術

2021-07-19 15:47:45

Python編程語言代碼

2018-10-18 11:20:06

編程語言代碼編碼秘訣

2022-03-29 18:18:07

Kubernetes框架

2019-10-18 10:04:45

Vim文本編輯器語言

2022-03-29 12:01:57

Vue 組件js組件工具集

2013-09-29 11:08:08

2018-06-16 08:35:57

UnixLinux命令

2020-06-18 15:53:06

Python代碼摳圖

2015-07-23 10:29:19

互聯(lián)網20年

2019-12-17 10:14:18

設計計算機CPU

2023-10-31 21:26:01

Prompt順序人工智能

2021-10-06 15:58:26

Python工具代碼

2022-04-12 08:43:21

Python內置模塊

2021-06-30 00:14:24

JS代碼數(shù)組

2020-05-13 15:52:18

編碼競賽網站代碼

2015-10-09 09:52:07

視覺設計好看

2017-08-18 15:54:16

RecyclerVieDiffUtil數(shù)據(jù)

2018-06-27 10:45:12

數(shù)據(jù)Python程序

2021-11-15 10:02:16

Python命令技巧
點贊
收藏

51CTO技術棧公眾號