Python:对列表分组、拆分
2021/10/1 20:11:17
本文主要是介绍Python:对列表分组、拆分,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
对列表的操作
- 1. 对列表元素分组
- 2. 多层列表展开成单层列表
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] # 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)
这篇关于Python:对列表分组、拆分的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python