假设我有一个这样的列表:
mylist = [2,3,4,7,8,9,0,1,2,3,10,11,12,20,19,18,17,17,18,19,20,21]
我想把它拆分成这样的子列表:
sublist_1 = [2,3,4]
sublist_2 = [7,8,9]
sublist_3 = [0,1,2,3]
sublist_4 = [10,11,12]
sublist_5 = [20,19,18,17]
sublist_5 = [17,18,19,20,21]
我该怎么做?
答案 0 :(得分:2)
代码 -
mylist = [2, 3, 4, 7, 8, 9, 0, 1, 2, 3, 10, 11, 12, 20, 19, 18, 17, 17, 18, 19,
20, 21]
result = []
temp_list = [mylist[0]]
for i in range(1, len(mylist)):
if abs(mylist[i] - mylist[i - 1]) != 1:
result.append(temp_list)
temp_list = [mylist[i]]
else:
temp_list.append(mylist[i])
if temp_list:
result.append(temp_list)
print(result)
输出 -
[[2, 3, 4], [7, 8, 9], [0, 1, 2, 3], [10, 11, 12], [20, 19, 18, 17],
[17, 18, 19, 20, 21]]
答案 1 :(得分:0)
这样做;
mylist = [2,3,4,7,8,9,0,1,2,3,10,11,12,20,19,18,17,17,18,19,20,21]
index =0
for i in range(0, len(mylist)):
#print (mylist[i+1])
if (i+1 >= len(mylist)):
print (mylist[index:i+1])
break
if not( (mylist[i+1] - mylist[i] == 1) or (mylist[i+1] - mylist[i] == -1) ):
print (mylist[index:i+1])
index = i+1
输出
[2, 3, 4]
[7, 8, 9]
[0, 1, 2, 3]
[10, 11, 12]
[20, 19, 18, 17]
[17, 18, 19, 20, 21]
答案 2 :(得分:0)
这是numpy
方法。我正在使用ediff1d,
intersect1d,nonzero
import numpy as np
mylist = [2, 3, 4, 7, 8, 9, 0, 1, 2, 3, 10, 11, 12, 20, 19, 18, 17, 17, 18, 19,
20, 21]
a = np.array(mylist)
t = np.ediff1d(mylist)
i = np.intersect1d(np.nonzero(t!=-1), np.nonzero(t!=1))
rslt = np.split(a,i+1)
rslt
Out[70]:
[array([2, 3, 4]),
array([7, 8, 9]),
array([0, 1, 2, 3]),
array([10, 11, 12]),
array([20, 19, 18, 17]),
array([17, 18, 19, 20, 21])]
如果您希望输出为list
而不是numpy array
,请将最后一行更改为rslt = [x.tolist() for x in np.split(a,i+1)]
,结果将为
rslt
Out[9]:
[[2, 3, 4],
[7, 8, 9],
[0, 1, 2, 3],
[10, 11, 12],
[20, 19, 18, 17],
[17, 18, 19, 20, 21]]