数据分析引发了复杂的场景,在这些场景中,数据需要整理才能移动。在这种情况下,让我们看看如何根据需要将一个大列表分成多个子列表。在本文中,我们将探讨实现这一目标的方法。
在这种方法中,我们使用列表切块从必须进行分割的位置获取元素。然后,我们使用zip和for循环使用for循环创建子列表。
Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]
# The indexes to split at
split_points = [2, 5, 8]
# Given list
print("Given list : " + str(Alist))
# SPlit at
print("The points of splitting : ",split_points)
#Perform the split
split_list = [Alist[i: j] for i, j in zip([0] +
split_points, split_points + [None])]
# printing result
print("The split lists are : ", split_list)输出结果
运行上面的代码给我们以下结果-
Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4] The points of splitting : [2, 5, 8] The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]
链函数使迭代器从第一个迭代器返回元素,直到用完为止。因此,它标记了发生分裂的点。然后,我们使用zip函数将拆分结果打包为子列表。
from itertools import chain
Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]
# The indexes to split at
split_points = [2, 5, 8]
# Given list
print("Given list : ", str(Alist))
# Split at
print("The points of splitting : ",split_points)
# to perform custom list split
sublists = zip(chain([0], split_points), chain(split_points, [None]))
split_list = list(Alist[i : j] for i, j in sublists)
# printing result
print("The split lists are : ", split_list)输出结果
运行上面的代码给我们以下结果-
Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4] The points of splitting : [2, 5, 8] The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]