根据条件将列表切片到子列表中

Huy*_*Bui 9 python list python-3.x

我想切这个数字列表:

num_list = [97, 122, 99, 98, 111, 112, 113, 100, 102] 
Run Code Online (Sandbox Code Playgroud)

分为多个子列表.切片的条件是每个子列表中的数字应按递增顺序排列.

所以最终结果将如下所示:

 list_1 = [97, 122]
 list_2 = [99]
 list_3 = [98, 111, 112, 113]
 list_4 = [100, 102]
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?非常感谢

Del*_*101 8

我很快写了一种方法来做到这一点,我相信有更有效的方法,但这至少有效:

num_list =[97, 122, 99, 98, 111, 112, 113, 100, 102]

arrays = [[num_list[0]]] # array of sub-arrays (starts with first value)
for i in range(1, len(num_list)): # go through each element after the first
    if num_list[i - 1] < num_list[i]: # If it's larger than the previous
        arrays[len(arrays) - 1].append(num_list[i]) # Add it to the last sub-array
    else: # otherwise
        arrays.append([num_list[i]]) # Make a new sub-array 
print(arrays)
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助:)


jpp*_*jpp 6

建议不要创建可变数量的变量.请改用列表或字典列表.这是一个带有dict生成器函数的示例:

from itertools import islice, zip_longest

def yield_lists(L):
    x = []
    for i, j in zip_longest(L, islice(L, 1, None), fillvalue=L[-1]):
        x.append(i)
        if i > j:
            yield x
            x = []
    yield x

num_list = [97, 122, 99, 98, 111, 112, 113, 100, 102]

res = dict(enumerate(yield_lists(num_list), 1))
Run Code Online (Sandbox Code Playgroud)

Resut:

{1: [97, 122],
 2: [99],
 3: [98, 111, 112, 113],
 4: [100, 102]}
Run Code Online (Sandbox Code Playgroud)

例如,通过访问第二个列表res[2].

  • 理想的解决方案,赢得发电机 (2认同)

Kas*_*mvd 6

这是一种单线性 Numpythonic 方法:

np.split(arr, np.where(np.diff(arr) < 0)[0] + 1)
Run Code Online (Sandbox Code Playgroud)

或者类似的 numpy 代码方法,但效率较低:

from operator import sub
from itertools import starmap
indices = [0] + [
                  i+1 for i, j in enumerate(list(
                        starmap(sub, zip(num_list[1:], num_list)))
                    ) if j < 0] + [len(num_list)
                ] + [len(num_list)]

result = [num_list[i:j] for i, j in zip(indices, indices[1:])]
Run Code Online (Sandbox Code Playgroud)

演示:

# Numpy
In [8]: np.split(num_list, np.where(np.diff(num_list) < 0)[0] + 1)
Out[8]: 
[array([ 97, 122]),
 array([99]),
 array([ 98, 111, 112, 113]),
 array([100, 102])]

# Python
In [42]: from operator import sub

In [43]: from itertools import starmap

In [44]: indices = [0] + [i+1 for i, j in enumerate(list(starmap(sub, zip(num_list[1:], num_list)))) if j < 0] + [len(num_list)]

In [45]: [num_list[i:j] for i, j in zip(indices, indices[1:])]
Out[45]: [[97, 122], [99], [98, 111, 112, 113], [100, 102]]
Run Code Online (Sandbox Code Playgroud)

解释:

使用np.diff()您可以获得每个项目与其下一个项目的差异(直到最后一个元素)。然后,您可以使用 numpy 的矢量化特性来获取这种差异为负的位置的索引,这可以通过简单的比较和 来完成np.where()。最后,您可以简单地将索引传递给以np.split()根据这些索引拆分数组。