Home > Software design >  Deleting sublists from a list
Deleting sublists from a list

Time:03-03

I want to delete sublists from a list whose length falls below a certain default value.

Below is a minimal working example. I would like to know if there is a more elegant and shorter way to accomplish this task?

In the example below, there are lists holding ten elements and that I want to keep. Lists that have fewer elements I want to delete.

def main():
    # Define lengths of lists
    list_lengths = [10, 6, 9, 10, 4, 2, 0, 10]

    nested_list = list(map(lambda x: list(range(x)), list_lengths))

    print("\nBefore deleting lists that are too short")
    for item in nested_list:
        print(item)
    print()

    # Get max length of all lists
    max_length = max(map(len, nested_list))

    print(f"max_length = {max_length}")

    idx_to_remove = list()
    for i, sublist in enumerate(nested_list):
        if len(sublist) < max_length:
            idx_to_remove.append(i)

    print(f"idx_to_remove = {idx_to_remove}")

    for i, idx in enumerate(idx_to_remove):
        del(nested_list[idx-i])

    print("\nAfter deleting lists that are too short")
    for item in nested_list:
        print(item)


if __name__ == "__main__":
    main()

CodePudding user response:

This is a two-liner :

max_length = max(map(len, nested_list))
nested_list = [i for i in nested_list if not len(i) < max_length]

This code has the exact same output than your sample :

def main():
    # Define lengths of lists
    list_lengths = [10, 6, 9, 10, 4, 2, 0, 10]

    nested_list = list(map(lambda x: list(range(x)), list_lengths))

    print("\nBefore deleting lists that are too short")
    for item in nested_list:
        print(item)
    print()

    nested_list = [i for i in nested_list if not len(i) < max(map(len, nested_list))]

    print("\nAfter deleting lists that are too short")
    for item in nested_list:
        print(item)

CodePudding user response:

You could use the filter function:

new_nested_list = filter(lambda x: len(x) == max(map(len, nested_list)), nested_list)
  • Related