# 检查两个字符串的组成元素是不是一样的
from collections import Counter
def similarConsistence(first, second):
return Counter(first) == Counter(second)
print(similarConsistence('abbc', 'cba')) # False
# 内存占用
import sys
variable = 3
print(sys.getsizeof(variable)) # 28, 单位为bytes
# 大写第一个字母
print('hello'.title())
# 列表分块
from math import ceil
def chunk(lst, size):
return list(map(lambda x: lst[x*size: x*size+size], list(range(0, ceil(len(lst)/size)))))
print(chunk([1, 2, 3, 4, 5], 2)) # [[1, 2], [3, 4], [5]]
# filter()
def is_odd(n):
return n % 2 == 1
print(list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))) # [1, 3, 5, 7, 9]
# 解包
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
print(list(zip(*array))) # [('a', 'c', 'e'), ('b', 'd', 'f')]
# 列表展开
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
print(deep_flatten([1, [2], [[3], 4], 5])) # [1,2,3,4,5]
# 列表的差
print(set([1, 2, 3]).difference(set([1, 2]))) # {3}
# 合并字典
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
最新推荐文章于 2025-04-17 23:47:50 发布