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

30個Python常用極簡代碼,拿走就用

開發(fā) 后端
本文是 30 個極簡任務(wù),初學(xué)者可以嘗試著自己實(shí)現(xiàn);本文同樣也是 30 段代碼,Python 開發(fā)者也可以看看是不是有沒想到的用法。

 [[333417]]

學(xué) Python 怎樣才最快,當(dāng)然是實(shí)戰(zhàn)各種小項(xiàng)目,只有自己去想與寫,才記得住規(guī)則。本文是 30 個極簡任務(wù),初學(xué)者可以嘗試著自己實(shí)現(xiàn);本文同樣也是 30 段代碼,Python 開發(fā)者也可以看看是不是有沒想到的用法。

1. 重復(fù)元素判定

以下方法可以檢查給定列表是不是存在重復(fù)元素,它會使用 set() 函數(shù)來移除所有重復(fù)元素。 

  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(first, second):  
  3. return Counter(first) == Counter(second)  
  4. anagram("abcd3", "3acdb") # True 

3.  內(nèi)存占用 

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

4.  字節(jié)占用

下面的代碼塊可以檢查字符串占用的字節(jié)數(shù)。 

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

5.  打印 N 次字符串

該代碼塊不需要循環(huán)語句就能打印 N 次字符串。 

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

6.  大寫第一個字母

以下代碼塊會使用 title() 方法,從而大寫字符串中每一個單詞的首字母。 

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

7.  分塊

給定具體的大小,定義一個函數(shù)以按照這個大小切割列表。 

  1. from math import ceil  
  2. def chunk(lst, size):  
  3. return list(  
  4. map(lambda x: lst[x * size:x * size + size],  
  5. list(range(0, ceil(len(lst) / size)))))  
  6. chunk([1,2,3,4,5],2)  
  7. # [[1,2],[3,4],5] 

8.  壓縮

這個方法可以將布爾型的值去掉,例如(False,None,0,“”),它使用 filter() 函數(shù)。 

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

9.  解包

如下代碼段可以將打包好的成對列表解開成兩組不同的元組。 

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

10.  鏈?zhǔn)綄Ρ?/strong>

我們可以在一行代碼中使用不同的運(yùn)算符對比多個不同的元素。 

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

11.  逗號連接

下面的代碼可以將列表連接成單個字符串,且每一個元素間的分隔方式設(shè)置為了逗號。 

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

12.  元音統(tǒng)計

以下方法將統(tǒng)計字符串中的元音 (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) 的個數(shù),它是通過正則表達(dá)式做的。 

  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.  首字母小寫

如下方法將令給定字符串的第一個字符統(tǒng)一為小寫。 

  1. def decapitalize(string):  
  2. return str[:1].lower() + str[1:]  
  3. decapitalize('FooBar') # 'fooBar' 
  4. 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.  列表的差

該方法將返回第一個列表的元素,其不在第二個列表內(nèi)。如果同時要反饋第二個列表獨(dú)有的元素,還需要加一句 set_b.difference(set_a)。 

  1. def difference(a, b):  
  2. setset_a = set(a)  
  3. setset_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ù)取差

如下方法首先會應(yīng)用一個給定的函數(shù),然后再返回應(yīng)用函數(shù)后結(jié)果有差別的列表元素。 

  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'])  
  7. # [ { x: 2 } ] 

17.  鏈?zhǔn)胶瘮?shù)調(diào)用

你可以在一行代碼內(nèi)調(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ù)項(xiàng)

如下代碼將檢查兩個列表是不是有重復(fù)項(xiàng)。 

  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 once from b  
  4. return c  
  5. a={'x':1,'y':2}  
  6. b={'y':3,'z':4}  
  7. print(merge_two_dicts(a,b))  
  8. #{'y':3,'x':1,'z':4} 

在 Python 3.5 或更高版本中,我們也可以用以下方式合并字典: 

  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))  
  6. # {'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))  
  6. #{'a': 2, 'c': 4, 'b': 3} 

21.  使用枚舉

我們常用 For 循環(huán)來遍歷某個列表,同樣我們也能枚舉列表的索引與值。 

  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í)行時間

如下代碼塊可以用來計算執(zhí)行特定代碼所花費(fèi)的時間。 

  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

我們在使用 try/except 語句的時候也可以加一個 else 子句,如果沒有觸發(fā)錯誤的話,這個子句就會被運(yùn)行。 

  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. 元素頻率

下面的方法會根據(jù)元素頻率取列表中最常見的元素。 

  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 的計算子

這一段代碼可以不使用條件語句就實(shí)現(xiàn)加減乘除、求冪操作,它通過字典這一數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn): 

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

27. Shuffle

該算法會打亂列表元素的順序,它主要會通過 Fisher-Yates 算法對新列表進(jìn)行排序: 

  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. -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.  展開列表

將列表內(nèi)的所有元素,包括子列表,都展開成一個列表。 

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

30.  字典默認(rèn)值

通過 Key 取對應(yīng)的 Value 值,可以通過以下方式設(shè)置默認(rèn)值。如果 get() 方法沒有設(shè)置默認(rèn)值,那么如果遇到不存在的 Key,則會返回 None。 

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

 

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

2021-12-13 23:02:41

Python語言開發(fā)

2020-08-17 10:50:29

Python代碼get

2022-05-01 21:49:06

Python

2022-02-18 11:51:36

Python代碼編程語言

2019-09-25 09:05:52

Python 機(jī)器學(xué)習(xí)編程語言

2021-04-23 22:44:57

Python開發(fā)辦公自動化

2020-06-23 11:30:38

Nginx高并發(fā)性能

2019-06-18 09:40:57

Graviton開源代碼編輯器

2020-04-29 14:50:40

代碼對比工具

2019-09-22 19:57:38

極簡代碼開發(fā)代碼

2016-12-06 10:07:01

銳捷網(wǎng)絡(luò)

2014-05-04 13:47:39

銳捷網(wǎng)絡(luò)極簡網(wǎng)絡(luò)

2016-12-28 10:00:03

銳捷網(wǎng)絡(luò)

2013-10-14 10:41:41

分配器buddy syste

2019-10-10 16:49:18

Python鏡音雙子腳本語言

2022-07-11 14:23:09

加密貨幣比特幣以太坊

2023-01-03 08:32:38

2022-01-26 10:52:21

代碼Python數(shù)據(jù)庫

2024-11-07 11:10:34

Python腳本統(tǒng)計分析

2023-06-23 14:02:57

OpenboxLinux發(fā)行版
點(diǎn)贊
收藏

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