打印乘法表
for i in range(1,10):
for j in range(1,i+1):
print(’{0}{1}={2}’.format(j,i,ji),end="\t")
print()
结果:
1*1=1
12=2 22=4
13=3 23=6 3*3=9
14=4 24=8 34=12 44=16
15=5 25=10 35=15 45=20 5*5=25
16=6 26=12 36=18 46=24 56=30 66=36
17=7 27=14 37=21 47=28 57=35 67=42 7*7=49
18=8 28=16 38=24 48=32 58=40 68=48 78=56 88=64
19=9 29=18 39=27 49=36 59=45 69=54 79=63 89=72 9*9=81
嵌套数组完全展开
from collections.abc import *
def flatten(input_arr, output_arr=None):
if output_arr is None:
output_arr = []
for ele in input_arr:
if isinstance(ele, Iterable): # 判断ele是否可迭代
flatten(ele, output_arr) # 尾数递归
else:
output_arr.append(ele) # 产生结果
return output_arr
flatten([[1,2,3],[4,5]], [6,7]) # [6, 7, 1, 2, 3, 4, 5]
将list等分为子组
from math import ceil
def divide(lst, size):
if size <= 0:
return [lst]
return [lst[i * size:(i+1)*size] for i in range(0, ceil(len(lst) / size))]
r = divide([1, 3, 5, 7, 9], 2) # [[1, 3], [5, 7], [9]]
生成fibonacci序列前n项
def fibonacci(n):
if n <= 1:
return [1]
fib = [1, 1]
while len(fib) < n:
fib.append(fib[len(fib) - 1] + fib[len(fib) - 2])
return fib
fibonacci(5) # [1, 1, 2, 3, 5]
过滤掉各种空值
def filter_false(lst):
return list(filter(bool, lst))
filter_false([None, 0, False, ‘’, [], ‘ok’, [1, 2]])# [‘ok’, [1, 2]]
返回列表头元素
def head(lst):
return lst[0] if len(lst) > 0 else None
head([]) # None
head([3, 4, 1]) # 3
返回列表尾元素
def tail(lst):
return lst[-1] if len(lst) > 0 else None
print(tail([])) # None
print(tail([3, 4, 1])) # 1
对象转换为可迭代类型
from collections.abc import Iterable
def cast_iterable(val):
return val if isinstance(val, Iterable) else [val]
cast_iterable(‘foo’)# foo
cast_iterable(12)# [12]
cast_iterable({‘foo’: 12})# {‘foo’: 12}
求更长列表
def max_length(*lst):
return max(*lst, key=lambda v: len(v))
r = max_length([1, 2, 3], [4, 5, 6, 7], [8])# [4, 5, 6, 7]
出现最多元素
def max_frequency(lst):
return max(lst, default=‘列表为空’, key=lambda v: lst.count(v))
lst = [1, 3, 3, 2, 1, 1, 2]
max_frequency(lst) # 1