简体   繁体   English

如何根据 Python 中的特定条件在更大的列表中分解列表?

[英]How do I break up a list within a larger list based on a specific condition in Python?

I have a list of lists my_list = [[1, 2, 3, 4], [8, 9], [89, 90]] .我有一个列表my_list = [[1, 2, 3, 4], [8, 9], [89, 90]] I want to break it up by scanning through each of the lists within the larger list.我想通过扫描较大列表中的每个列表来分解它。 If a condition is met (for example, if 3 is found), I want to break up that inner list into two lists.如果满足条件(例如,如果找到3 ),我想将该内部列表分成两个列表。

The desired end result should be [[1, 2], [3, 4], [8, 9], [89, 90]] .期望的最终结果应该是[[1, 2], [3, 4], [8, 9], [89, 90]]

But my code below:但我的代码如下:

def break_list_by_specific_number(list_of_lists, break_num):
    list_holder = []
    for each_list in list_of_lists:
        i = (list(g) for _, g in groupby(each_list, key=break_num.__ne__))
        list_holder += ([a + b for a, b in zip_longest(i, i, fillvalue=[])])
    return list_holder

print(break_list_by_specific_number(my_list, 3))

It breaks it up incorrectly into [[1, 2, 3], [4], [8, 9], [89, 90]] .它错误地将其分解为[[1, 2, 3], [4], [8, 9], [89, 90]]

You can write this much faster and a lot simpler this way:你可以这样写得更快、更简单:

def break_list(array, break_num):
    out = []
    for inner in array:
        if break_num in inner:
            index = inner.index(break_num)
            first = inner[:index]
            second = inner[index:]
            out.append(first)
            out.append(second)
        else:
            out.append(inner)
    return out

This assumes that there is at most 1 instance of break_num in inner and that array is a 2D list.这假设inner最多有 1 个break_num实例,并且该array是一个二维列表。

You call this the same way you were originally calling it and it works just fine.你调用它的方式与你最初调用它的方式相同,它工作得很好。

>>> arr = [[1, 2, 3, 4], [8, 9], [89, 90]]
>>> break_list(arr, 3)
[[1, 2], [3, 4], [8, 9], [89, 90]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM