简体   繁体   中英

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

The desired end result should be [[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]] .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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