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

30秒內(nèi)便能學(xué)會的30個實用Python代碼片段

開發(fā) 后端
許多人在數(shù)據(jù)科學(xué)、機器學(xué)習(xí)、web開發(fā)、腳本編寫和自動化等領(lǐng)域中都會使用Python,它是一種十分流行的語言。

許多人在數(shù)據(jù)科學(xué)、機器學(xué)習(xí)、web開發(fā)、腳本編寫和自動化等領(lǐng)域中都會使用Python,它是一種十分流行的語言。

[[278724]]

Python流行的部分原因在于簡單易學(xué)。

本文將簡要介紹30個簡短的、且能在30秒內(nèi)掌握的代碼片段。

1. 唯一性

以下方法可以檢查給定列表是否有重復(fù)的地方,可用set()的屬性將其從列表中刪除。

  1. def all_unique(lst): 
  2.  return len(lst) == len(set(lst)) 
  3. x = [1,1,2,2,3,2,3,4,5,6] 
  4. y = [1,2,3,4,5] 
  5. all_unique(x) # False 
  6. all_unique(y) # True 

2. 變位詞(相同字母異序詞)

此方法可用于檢查兩個字符串是否為變位詞。

  1. from collections import Counter 
  2. def anagram(firstsecond): 
  3.  return Counter(first) == Counter(second
  4. anagram("abcd3""3acdb") # True 

3. 內(nèi)存

此代碼段可用于檢查對象的內(nèi)存使用情況。

  1. import sys  
  2. variable = 30  
  3. print(sys.getsizeof(variable)) # 24 

4. 字節(jié)大小

此方法可輸出字符串的字節(jié)大小。

  1. def byte_size(string): 
  2.  return(len(string.encode('utf-8'))) 
  3. byte_size('') # 4 
  4. byte_size('Hello World') # 11 

5. 打印N次字符串

此代碼段無需經(jīng)過循環(huán)操作便可多次打印字符串。

  1. n = 2;  
  2. s ="Programming";  
  3. print(s * n); # ProgrammingProgramming 

6. 首字母大寫

以下代碼片段只利用了title(),就能將字符串中每個單詞的首字母大寫。

  1. s = "programming is awesome" 
  2. print(s.title()) # Programming Is Awesome 

7. 列表細分

該方法將列表細分為特定大小的列表。

  1. def chunk(list, size): 
  2.  return [list[i:i+sizefor i in range(0,len(list), size)] 

8. 壓縮

以下代碼使用filter()從,將錯誤值(False、None、0和“ ”)從列表中刪除。

  1. def compact(lst): 
  2.  return list(filter(bool, lst)) 
  3. compact([0, 1, False, 2, '', 3, 'a''s', 34]) # [ 1, 2, 3, 'a''s', 34 ] 

9. 計數(shù)

以下代碼可用于調(diào)換2D數(shù)組排列。

  1. array = [['a''b'], ['c''d'], ['e''f']] 
  2. transposed = zip(*array) 
  3. print(transposed) # [('a''c''e'), ('b''d''f')] 

10. 鏈式比較

以下代碼可對各種運算符進行多次比較。

  1. a = 3 
  2. print( 2 < a < 8) # True 
  3. print(1 == a < 2) # False 

11. 逗號分隔

此代碼段可將字符串列表轉(zhuǎn)換為單個字符串,同時將列表中的每個元素用逗號隔開。

  1. hobbies = ["basketball""football""swimming"
  2. print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming 

12. 元音計數(shù)

此方法可計算字符串中元音(“a”、“e”、“i”、“o”、“u”)的數(shù)目。

  1. import re 
  2. def count_vowels(str): 
  3.  return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)) 
  4. count_vowels('foobar') # 3 
  5. count_vowels('gym') # 0 

13. 首字母小寫

此方法可將給定字符串的首字母轉(zhuǎn)換為小寫模式。

  1. def decapitalize(string): 
  2.  return str[:1].lower() + str[1:] 
  3.   
  4. decapitalize('FooBar') # 'fooBar' 
  5. decapitalize('FooBar') # 'fooBar' 

14. 展開列表

下列代碼采用了遞歸法展開潛在的深層列表。

  1. def spread(arg): 
  2.  ret = [] 
  3.  for i in arg: 
  4.  if isinstance(i, list): 
  5.  ret.extend(i) 
  6.  else
  7.  ret.append(i) 
  8.  return ret 
  9. def deep_flatten(lst): 
  10.  result = [] 
  11.  result.extend( 
  12.  spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) 
  13.  return result 
  14. deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] 

15. 尋找差異

此方法僅保留第一個迭代中的值來查找兩個迭代之間的差異。

  1. def difference(a, b): 
  2.  set_a = set(a) 
  3.  set_b = set(b) 
  4.  comparison = set_a.difference(set_b) 
  5.  return list(comparison) 
  6. difference([1,2,3], [1,2,4]) # [3] 

16. 輸出差異

以下方法利用已有函數(shù),尋找并輸出兩個列表之間的差異。

  1. def difference_by(a, b, fn): 
  2.  b = set(map(fn, b)) 
  3.  return [item for item in a if fn(item) not in b] 
  4. from math import floor 
  5. difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2] 
  6. difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ] 

17. 鏈式函數(shù)調(diào)用

以下方法可以實現(xiàn)在一行中調(diào)用多個函數(shù)。

  1. def add(a, b): 
  2.  return a + b 
  3. def subtract(a, b): 
  4.  return a – b 
  5. a, b = 4, 5 
  6. print((subtract if a > b else add)(a, b)) # 9  

18. 重復(fù)值存在與否

以下方法利用set()只包含唯一元素的特性來檢查列表是否存在重復(fù)值。

  1. def has_duplicates(lst): 
  2.  return len(lst) != len(set(lst)) 
  3. x = [1,2,3,4,5,5] 
  4. y = [1,2,3,4,5] 
  5. has_duplicates(x) # True 
  6. has_duplicates(y) # False 

19. 合并字庫

以下方法可將兩個字庫合并。

  1. def merge_two_dicts(a, b): 
  2.  c = a.copy() # make a copy of a  
  3.  c.update(b) # modify keys and values of a with the ones from b 
  4.  return c 
  5. a = { 'x': 1, 'y': 2} 
  6. b = { 'y': 3, 'z': 4} 
  7. print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4} 

在Python3.5及升級版中,也可按下列方式執(zhí)行步驟代碼:

  1. def merge_dictionaries(a, b) 
  2.  return {**a, **b} 
  3. a = { 'x': 1, 'y': 2} 
  4. b = { 'y': 3, 'z': 4} 
  5. print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4} 

20. 將兩個列表轉(zhuǎn)換為字庫

以下方法可將兩個列表轉(zhuǎn)換為字庫。

  1. def to_dictionary(keys, values): 
  2.  return dict(zip(keys, values)) 
  3. keys = ["a""b""c"]  
  4. values = [2, 3, 4] 
  5. print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3} 

21. 列舉

以下代碼段可以采用列舉的方式來獲取列表的值和索引。

  1. list = ["a""b""c""d"
  2. for index, element in enumerate(list):  
  3.  print("Value", element, "Index "index, ) 
  4. # ('Value''a''Index ', 0) 
  5. # ('Value''b''Index ', 1) 
  6. #('Value''c''Index ', 2) 
  7. # ('Value''d''Index ', 3)  

22. 時間成本

以下代碼可計算執(zhí)行特定代碼所需的時間。

  1. import time 
  2. start_time = time.time() 
  3. a = 1 
  4. b = 2 
  5. c = a + b 
  6. print(c) #3 
  7. end_time = time.time() 
  8. total_time = end_time - start_time 
  9. print("Time: ", total_time) 
  10. # ('Time: ', 1.1205673217773438e-05) 

23. Try else語句

可將else句作為try/except語句的一部分,如果沒有異常情況,則執(zhí)行else語句。

  1. try: 
  2.  2*3 
  3. except TypeError: 
  4.  print("An exception was raised"
  5. else
  6.  print("Thank God, no exceptions were raised."
  7. #Thank God, no exceptions were raised. 

24. 出現(xiàn)頻率很高的元素

此方法將輸出列表中出鏡率很高的元素。

  1. def most_frequent(list): 
  2.  return max(set(list), key = list.count
  3. list = [1,2,1,2,3,2,1,4,2] 
  4. most_frequent(list)  

25. 回文(正反讀有一樣的字符串)

以下代碼檢查給定字符串是否為回文。首先將字符串轉(zhuǎn)換為小寫,然后從中刪除非字母字符,最后將新字符串版本與原版本進行比對。

  1. def palindrome(string): 
  2.  from re import sub 
  3.  s = sub('[\W_]''', string.lower()) 
  4.  return s == s[::-1] 
  5. palindrome('taco cat') # True 

26. 不用if-else語句的計算器

以下代碼片段展示了如何在不用if-else條件語句的情況下,編寫簡易計算器。

  1. import operator 
  2. action = { 
  3.  "+": operator.add
  4.  "-": operator.sub, 
  5.  "/": operator.truediv, 
  6.  "*": operator.mul, 
  7.  "**": pow 
  8. print(action['-'](50, 25)) # 25 

27. 隨機排序

該算法采用Fisher-Yates algorithm對新列表中的元素進行隨機排序。

  1. from copy import deepcopy 
  2. from random import randint 
  3. def shuffle(lst): 
  4.  temp_lst = deepcopy(lst) 
  5.  m = len(temp_lst) 
  6.  while (m): 
  7.  m -= 1 
  8.  i = randint(0, m) 
  9.  temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] 
  10.  return temp_lst 
  11. foo = [1,2,3] 
  12. shuffle(foo) # [2,3,1] , foo = [1,2,3] 

28. 展開列表

此方法將類似javascript中[].concat(…arr)這樣的列表展開。

  1. def spread(arg): 
  2.  ret = [] 
  3.  for i in arg: 
  4.  if isinstance(i, list): 
  5.  ret.extend(i) 
  6.  else
  7.  ret.append(i) 
  8.  return ret 
  9. spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] 

29. 交換變量

此方法為能在不使用額外變量的情況下快速交換兩種變量。

  1. def swap(a, b): 
  2.  return b, a 
  3. a, b = -1, 14 
  4. swap(a, b) # (14, -1) 

30. 獲取丟失部分的默認值

以下代碼可在所需對象不在字庫范圍內(nèi)的情況下獲取默認值。

  1. d = {'a': 1, 'b': 2} 
  2. print(d.get('c', 3)) # 3 

本文只簡單介紹了一些能在日常工作中幫到我們的方法。但內(nèi)容都主要立足于GitHub 存儲庫:https://github.com/30-seconds/30_seconds_of_knowledge,該存儲庫還包含了有關(guān)Python及其他語言和技術(shù)行之有效的代碼。

 

責(zé)任編輯:華軒 來源: 今日頭條
相關(guān)推薦

2024-05-06 10:11:51

2023-06-16 16:34:25

JavaScripWeb 開發(fā)

2023-11-03 16:02:00

JavaScript開發(fā)

2021-03-19 09:53:28

Python 開發(fā)編程語言

2022-02-18 11:51:36

Python代碼編程語言

2023-10-09 14:48:06

2023-10-10 16:16:05

JavaScrip開發(fā)

2013-11-13 16:57:16

2017-12-14 17:14:32

GithubJavaScript程序員

2012-02-07 14:04:53

CSS

2012-11-27 10:23:18

CSSWeb開發(fā)

2020-05-28 08:59:40

Python機器學(xué)習(xí)開發(fā)

2023-03-06 21:38:26

Python文件碼率mp3

2013-03-20 09:40:46

HTMLCSS工具

2021-09-22 09:43:47

Python 開發(fā)編程語言

2015-11-02 09:25:07

jQuery代碼片段

2015-10-08 08:53:46

PHP代碼片段

2011-07-07 10:35:53

htaccess

2020-04-13 14:45:12

Python技巧代碼

2023-08-26 07:22:44

出碼率MP3算法
點贊
收藏

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