from math import ceil # 返回不小于本身的数值
def divide_iter(lst, n):
if n <= 0: # 直接返回列表
yield lst
return
i, div = 0, ceil(len(lst)/n) # 分组
while i < n:
yield lst[i * div: (i+1)*div] # list[0:3],[3:6]
i += 1
iter = list(divide_iter([1, 2, 3, 4, 5], 2))
print("list分组:", iter)
# 原数据:d = [7,9,8,4,6,5,1,2,3,8,4,8,9,4,6,5]
# 要求把数据有序的分为4组
d = [7,9,8,4,6,5,1,2,3,8,4,8,9,4,6,5]
print("有序的分为4组:", list(divide_iter(sorted(d), 4)))
2. 多层列表展开成单层列表
# 多层列表展开成单层列表
t = [1,2,[3,4,[5,6],7],8,["python",6],9]
def function(lst):
for i in lst:
if type(i)==list:
yield from function(i)
else:
yield i
result = list(function(t))
print("拆分:", result)