Home > Software engineering >  How to split list based on values in Python?
How to split list based on values in Python?

Time:05-27

I have a list that needs to copied multiply times by the number at an index. here is an example to help explain.

The original list:

[AAA, Bus, Apple, 5, 3, 1, Car, 22, 30]

what is needs to become:

aList = [
[AAA, Bus, Apple, 1, 1, 1, Car, 22, 30]
[AAA, Bus, Apple, 1, 1, 0, Car, 22, 30]
[AAA, Bus, Apple, 1, 1, 0, Car, 22, 30]
[AAA, Bus, Apple, 1, 0, 0, Car, 22, 30]
[AAA, Bus, Apple, 1, 0, 0, Car, 22, 30]
]

All the list are in the same order to I can view the values bu index. Thanks

CodePudding user response:

I hope I've understood your question right. This example will copy the list by maximal number found in list:

lst = ["AAA", "Bus", "Apple", 5, 3, 1, "Car"]

n = max((v for v in lst if isinstance(v, int)), default=0)

out = [lst]
for _ in range(n - 1):
    out.append([(v - 1) if isinstance(v, int) else v for v in out[-1]])

out = [[int(v > 0) if isinstance(v, int) else v for v in l] for l in out]

print(*out, sep="\n")

Prints:

['AAA', 'Bus', 'Apple', 1, 1, 1, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']

EDIT: To change only specified indices:

lst = ["AAA", "Bus", "Apple", 5, 3, 1, "Car"]

n = max(v for v in lst[3:6])

out = [lst[3:6]]
for _ in range(n - 1):
    out.append([v - 1 for v in out[-1]])

out = [lst[:3]   [int(v > 0) for v in l]   lst[6:] for l in out]

print(*out, sep="\n")

Prints:

['AAA', 'Bus', 'Apple', 1, 1, 1, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']
  • Related