1. 对列表元素分组
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]
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]
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)
|