Python是目前最流行的语言之一,它在数据科学、机器学习、web开发、脚本编写、自动化方面被许多人广泛使用。 它的简单和易用性造就了它如此流行的原因。 如果你正在阅读本文,那么你或多或少已经使用过Python或者对Python感兴趣。 在本文中,我们将会介绍 30 个简短的代码片段,你可以在 30 秒或更短的时间里理解和学习这些代码片段。 接上篇:超实用的 30 段 Python 案例(上) 16.寻找差异下面的方法在将给定的函数应用于两个列表的每个元素后,返回两个列表之间的差值。 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.链式函数调用以下方法可在一行中调用多个函数。 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.检查重复值以下方法使用 set() 方法仅包含唯一元素的事实来检查列表是否具有重复值。 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及更高版本中,你还可以执行以下操作: 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.将两个列表转换成一个词典以下方法可将两个列表转换成一个词典。 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.计算所需时间以下代码段可用于计算执行特定代码所需的时间。 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 块的一部分,如果没有抛出异常,则执行该子句。 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.查找最常见元素以下方法返回列表中出现的最常见元素。 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.回文以下方法可检查给定的字符串是否为回文结构。该方法首先将字符串转换为小写,然后从中删除非字母数字字符。最后,它会将新的字符串与反转版本进行比较。 def palindrome(string): from re import sub s = sub('[W_]', '', string.lower()) return s == s[::-1] palindrome('taco cat') # True
26.没有 if-else 语句的简单计算器以下代码段将展示如何编写一个不使用 if-else 条件的简单计算器。 import operator action = { '+': operator.add, '-': operator.sub, '/': operator.truediv, '*': operator.mul, '**': pow } print(action['-'](50, 25)) # 25
27.元素顺序打乱以下算法通过实现 Fisher-Yates算法 在新列表中进行排序来将列表中的元素顺序随机打乱。 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.获取缺失键的默认值以下代码段显示了如何在字典中没有包含要查找的键的情况下获得默认值。 d = {'a': 1, 'b': 2} print(d.get('c', 3)) # 3
接上篇:超实用的 30 段 Python 案例(上) 关注作者新号:web前端营 获取海量IT类教程 都来到这了,拜托拜托关注下 点赞和在看就是最大的支持❤️
|