变位词
检测两个字符串是否互为变位词
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
print(anagram('abcd3', '3acdb'))
# True
分块
使用range()将列表分块为指定大小的较小列表
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]]
间隔数
转换一个二维数组
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed)
# [('a', 'c', 'e'), ('b', 'd', 'f')]
首字母恢复小写
将给定字符串的第一个字母转换为小写
def decapitalize(str):
return str[:1].lower() + str[1:]
decapitalize('FooBar')
# fooBar
filter()删除列表中错误值
如(:False, None, 0, 和’’)
def compact(lst):
return list(filter(bool, lst))
print(compact([0, 1, False, 2, '', 3, 'a', 's', 34]))
# [1, 2, 3, 'a', 's', 34]
递归展开潜在列表
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]
差异
两个列表进行对比,保留第一个
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
print(difference([1, 2, 3], [1, 2, 4]))
# 3
查找出现最多的元素
def most_frequent(list):
return max(set(list), key = list.count)
lst = [1, 2, 1, 2, 3, 2, 1, 4, 2]
print(most_frequent(lst)
# 2
变量交换
def swap(a, b):
return b, a
a, b= -1, 14
print(swap(a, b)
# (14, -1)