Python 列表切割:按元素条件划分成多个子列表
你可以使用循环遍历列表,并根据特定条件将元素切割成多个子列表。下面是一个示例:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sub_lists = []
current_sub_list = []
for item in my_list:
if item % 2 == 0: # 根据特定条件进行切割,这里以元素是否为偶数为例
if current_sub_list: # 如果当前子列表不为空,则将其添加到结果列表中
sub_lists.append(current_sub_list)
current_sub_list = [] # 重置当前子列表
current_sub_list.append(item) # 将元素添加到当前子列表中
if current_sub_list: # 处理最后一个子列表
sub_lists.append(current_sub_list)
print(sub_lists)
输出结果为:
[[1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
在这个示例中,我们将列表中的元素按照是否为偶数进行切割成多个子列表。每当遇到一个偶数时,我们将当前子列表添加到结果列表中,并创建一个新的空子列表。最后,我们检查一下最后一个子列表是否为空,并将其添加到结果列表中。
原文地址: http://www.cveoy.top/t/topic/IAs 著作权归作者所有。请勿转载和采集!