例如:
比如列表[0,0,0,1,1,2,3,3,3,2,3,3,0,0]
分割成[[0,0,0],[1,1],[2],[3,3,3],[2],[3,3],[0,0]]
list1 = [0,0,0,1,1,2,3,3,3,2,3,3,0,0]
sub=[list1[0]]
new1=[]
for i in range(1,len(list1)):
#列表的每个元素与sub的末尾元素匹配,如果相等,那么添加到sub里面
if list1[i]==sub[-1]:
sub.append(list1[i])
# 否则,将sub添加到new1当中,并给sub重新赋予一个新值
else:
new1.append(sub)
sub=[list1[i]]
new1.append(sub)
print(new1)
>>> 结果如下:
[[0, 0, 0], [1, 1], [2], [3, 3, 3], [2], [3, 3], [0, 0]]