01 重复元素判定
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True
02 字符元素组成判定
检查两个字符串的组成元素是不是一样的。
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
03 内存占用
下面的代码块可以检查变量 variable 所占用的内存。
import sys
variable = 30
print(sys.getsizeof(variable)) # 24
04 字节占用
下面的代码块可以检查字符串占用的字节数。
def byte_size(string):
return(len(string.encode('utf-8')))
byte_size('😀') # 4
byte_size('Hello World') # 11
05 通过函数取差
如下方法首先会应用一个给定的函数,然后再返回应用函数后结果有差别的列表元素。
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 } ]
06 检查重复项
如下代码将检查两个列表是不是有重复项。
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
07 合并两个字典
下面的方法将用于合并两个字典。
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}
#第二种方式
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}
本文精选了Python编程中实用且高效的一些技巧,包括列表去重、字符串元素比较、内存占用检查、字节大小测量、列表差集获取、重复项检查、字典合并等,帮助开发者提升代码质量和效率。

被折叠的 条评论
为什么被折叠?



