def spread(arg): ret = [] for i in arg: if isinstance(i, list): ret.extend(i) else: ret.append(i) return ret def deep_flatten(lst): result = [] result.extend( spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) return result deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
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 } ]
链式函数调用
你可以在一行代码内调用多个函数。
1 2 3 4 5 6
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
检查重复项
如下代码将检查两个列表是不是有重复项。
1 2 3 4 5 6
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
合并两个字典
下面的方法将用于合并两个字典。
1 2 3 4 5 6 7 8
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 once 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 或更高版本中,我们也可以用以下方式合并字典:
1 2 3 4 5 6
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}
try: 2*3 except TypeError: print("An exception was raised") else: print("Thank God, no exceptions were raised.") #Thank God, no exceptions were raised.
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]
展开列表
将列表内的所有元素,包括子列表,都展开成一个列表。
1 2 3 4 5 6 7 8
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]
交换值
不需要额外的操作就能交换两个变量的值。
1 2 3 4 5
def swap(a, b): return b, a a, b = -1, 14 swap(a, b) # (14, -1) spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
字典默认值
通过 Key 取对应的 Value 值,可以通过以下方式设置默认值。如果 get() 方法没有设置默认值,那么如果遇到不存在的 Key,则会返回 None。