如何在Python3中按数字顺序查找列表中的数字?

时间:2021-08-27 07:43:43

I have a list, like this:

我有一个列表,像这样:

list_1 = [1,2,2,3,1,2]

I want to create another nested lists like this:

我想创建另一个嵌套列表,如下所示:

[[1,2,2,1,2],[2,2,3,2]]

The first nested list is only composed of 1 and 2 because, according to the numerical order, 2 comes after 1 and 1 is must be included. 3 is not in the first nested list because after 1 comes 2 and not 3.

第一个嵌套列表仅由1和2组成,因为根据数字顺序,2在1之后,1必须包含。 3不在第一个嵌套列表中,因为1之后是2而不是3。

In the second nested list, there is 2 and 3 because 3 comes after 2 and 2 needs to be included. 1 is not there because one doesn't come after 2.

在第二个嵌套列表中,有2个和3个,因为3个在2之后,需要包含2个。 1不存在,因为一个人不会在2之后来。

How can I achieve this in Python 3?

我怎样才能在Python 3中实现这一点?

2 个解决方案

#1


2  

list_1 = [1,2,2,3,1,2]

m = max(list_1)
print([[i for i in list_1 if i in [j,j+1] ] for j in range(1,m)])

#[[1, 2, 2, 1, 2], [2, 2, 3, 2]]




#list_1 = [1,2,2,3,1,2,4,2,3,6,5,4]
#->[[1, 2, 2, 1, 2, 2], [2, 2, 3, 2, 2, 3], [3, 4, 3, 4], [4, 5, 4], [6, 5]]

#2


1  

If you can go without a functional one liner, you could do it like this.

如果你没有功能性的衬垫,你就可以这样做。

def listsep(lst, sep):

    l1 = []
    l2 = []

    for v in lst:
        if v <= sep:
            l1.append(v)

        if v >= sep:
            l2.append(v)


    return [l1, l2]

print(listsep([1,2,2,3,1,2], 2))

Just iterate the input and append to each list if less than/equal or greater than/equal. This iterates the input only once.

只需迭代输入并附加到每个列表,如果小于/等于或大于/等于。这只迭代输入一次。

#1


2  

list_1 = [1,2,2,3,1,2]

m = max(list_1)
print([[i for i in list_1 if i in [j,j+1] ] for j in range(1,m)])

#[[1, 2, 2, 1, 2], [2, 2, 3, 2]]




#list_1 = [1,2,2,3,1,2,4,2,3,6,5,4]
#->[[1, 2, 2, 1, 2, 2], [2, 2, 3, 2, 2, 3], [3, 4, 3, 4], [4, 5, 4], [6, 5]]

#2


1  

If you can go without a functional one liner, you could do it like this.

如果你没有功能性的衬垫,你就可以这样做。

def listsep(lst, sep):

    l1 = []
    l2 = []

    for v in lst:
        if v <= sep:
            l1.append(v)

        if v >= sep:
            l2.append(v)


    return [l1, l2]

print(listsep([1,2,2,3,1,2], 2))

Just iterate the input and append to each list if less than/equal or greater than/equal. This iterates the input only once.

只需迭代输入并附加到每个列表,如果小于/等于或大于/等于。这只迭代输入一次。