拆分包含连续块项的列表,但将已停止的块拆分为子列表

时间:2016-06-02 15:05:00

标签: python algorithm sorting

假设我有一个这样的列表:

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]

我该怎么做?

3 个答案:

答案 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方法。我正在使用ediff1dintersect1dnonzero

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]]