Python是目前最流行的語言之一,它在數(shù)據(jù)科學(xué)、機(jī)器學(xué)習(xí)、web開發(fā)、腳本編寫、自動化方面被許多人廣泛使用。 它的簡單和易用性造就了它如此流行的原因。 如果你正在閱讀本文,那么你或多或少已經(jīng)使用過Python或者對Python感興趣。 在本文中,我們將會介紹 30 個簡短的代碼片段,你可以在 30 秒或更短的時(shí)間里理解和學(xué)習(xí)這些代碼片段。 接上篇:超實(shí)用的 30 段 Python 案例(上) 16.尋找差異下面的方法在將給定的函數(shù)應(yīng)用于兩個列表的每個元素后,返回兩個列表之間的差值。 def difference_by(a, b, fn): b = set(map(fn, b)) return [item for item in a if fn(item) not in b] from math import floor difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2] difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
17.鏈?zhǔn)胶瘮?shù)調(diào)用以下方法可在一行中調(diào)用多個函數(shù)。 def add(a, b): return a + b def subtract(a, b): return a - b a, b = 4, 5 print((subtract if a > b else add)(a, b)) # 9
18.檢查重復(fù)值以下方法使用 set() 方法僅包含唯一元素的事實(shí)來檢查列表是否具有重復(fù)值。 def has_duplicates(lst): return len(lst) != len(set(lst)) x = [1,2,3,4,5,5] y = [1,2,3,4,5] has_duplicates(x) # True has_duplicates(y) # False
19.合并兩個詞典以下方法可用于合并兩個詞典。 def merge_two_dicts(a, b): c = a.copy() # make a copy of a c.update(b) # modify keys and values of a with the ones from b return c a = { 'x': 1, 'y': 2} b = { 'y': 3, 'z': 4} print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
在Python 3.5及更高版本中,你還可以執(zhí)行以下操作: def merge_dictionaries(a, b) return {**a, **b} a = { 'x': 1, 'y': 2} b = { 'y': 3, 'z': 4} print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
20.將兩個列表轉(zhuǎn)換成一個詞典以下方法可將兩個列表轉(zhuǎn)換成一個詞典。 def to_dictionary(keys, values): return dict(zip(keys, values)) keys = ['a', 'b', 'c'] values = [2, 3, 4] print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}
21.使用枚舉以下方法將字典作為輸入,然后僅返回該字典中的鍵。 list = ['a', 'b', 'c', 'd'] for index, element in enumerate(list): print('Value', element, 'Index ', index, ) # ('Value', 'a', 'Index ', 0) # ('Value', 'b', 'Index ', 1) #('Value', 'c', 'Index ', 2) # ('Value', 'd', 'Index ', 3)
22.計(jì)算所需時(shí)間以下代碼段可用于計(jì)算執(zhí)行特定代碼所需的時(shí)間。 import time start_time = time.time() a = 1 b = 2 c = a + b print(c) #3 end_time = time.time() total_time = end_time - start_time print('Time: ', total_time) # ('Time: ', 1.1205673217773438e-05)
23.Try else 指令你可以將 else 子句作為 try/except 塊的一部分,如果沒有拋出異常,則執(zhí)行該子句。 try: 2*3 except TypeError: print('An exception was raised') else: print('Thank God, no exceptions were raised.') #Thank God, no exceptions were raised.
24.查找最常見元素以下方法返回列表中出現(xiàn)的最常見元素。 def most_frequent(list): return max(set(list), key = list.count) list = [1,2,1,2,3,2,1,4,2] most_frequent(list)
25.回文以下方法可檢查給定的字符串是否為回文結(jié)構(gòu)。該方法首先將字符串轉(zhuǎn)換為小寫,然后從中刪除非字母數(shù)字字符。最后,它會將新的字符串與反轉(zhuǎn)版本進(jìn)行比較。 def palindrome(string): from re import sub s = sub('[W_]', '', string.lower()) return s == s[::-1] palindrome('taco cat') # True
26.沒有 if-else 語句的簡單計(jì)算器以下代碼段將展示如何編寫一個不使用 if-else 條件的簡單計(jì)算器。 import operator action = { '+': operator.add, '-': operator.sub, '/': operator.truediv, '*': operator.mul, '**': pow } print(action['-'](50, 25)) # 25
27.元素順序打亂以下算法通過實(shí)現(xiàn) Fisher-Yates算法 在新列表中進(jìn)行排序來將列表中的元素順序隨機(jī)打亂。 from copy import deepcopy from random import randint def shuffle(lst): temp_lst = deepcopy(lst) m = len(temp_lst) while (m): m -= 1 i = randint(0, m) temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] return temp_lst foo = [1,2,3] shuffle(foo) # [2,3,1] , foo = [1,2,3]
28.列表扁平化以下方法可使列表扁平化,類似于JavaScript中的[].concat(…arr)。 def spread(arg): ret = [] for i in arg: if isinstance(i, list): ret.extend(i) else: ret.append(i) return ret spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
29.變量交換以下是交換兩個變量的快速方法,而且無需使用額外的變量。 def swap(a, b): return b, a a, b = -1, 14 swap(a, b) # (14, -1)
30.獲取缺失鍵的默認(rèn)值以下代碼段顯示了如何在字典中沒有包含要查找的鍵的情況下獲得默認(rèn)值。 d = {'a': 1, 'b': 2} print(d.get('c', 3)) # 3
接上篇:超實(shí)用的 30 段 Python 案例(上) 關(guān)注作者新號:web前端營 獲取海量IT類教程 都來到這了,拜托拜托關(guān)注下 點(diǎn)贊和在看就是最大的支持??
|