将26个字母按照n个分成一组1.按照基础的方法
1 def group(list,n): 2 H = [] 3 s = len(list)/n 4 if len(list)%n ==0: 5 for i in range(s): 6 li = list[i*n:(i+1)*n] 7 H.append(li) 8 else: 9 for i in range(s): 10 li = list[i*n:(i+1)*n] 11 H.append(li) 12 H.append(list[-s*n:]) 13 return H
2.使用zip方法
1 #使用zip合并相邻的项(好像只能是迭代对象iter) 2 3 def group(lst, n): 4 num = len(lst) % n 5 zipped = zip(*[iter(lst)] * n) 6 if num == 0: 7 return zipped 8 else: 9 return zipped + [lst[-num:], ]
时间: 2024-10-09 00:21:34