0

Example given

list = [[2, 3, 4], [3,4,5,6,7]]

I want to split chunks in the given example list if any chunk has a value greater than value 4.

So output should be

[[2, 3, 4], [3,4], [5, 6,7]].

Somehow i got required answer, But, I just want to know,

Is there any single line statement or function in 'Python' which will give required output based on given condition?

Naaga A
  • 552
  • 1
  • 5
  • 13

2 Answers2

1

As someone in the comments suggested, other ways to do this would be more readable, but I've being playing on how to do this with one line of code just for fun:

list = [[2, 3, 4], [3,4,5,6,7]]
new_list = [a for b in [[[x for x in y if x <= 4], [x for x in y if x > 4]] for y in list] for a in b if a]
print(new_list)

result: [[2, 3, 4], [3, 4], [5, 6, 7]]

migjimen
  • 551
  • 1
  • 4
  • 6
0

You should probably use a chunking generator

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

Then you can feed your list through a generator function that will chunk at the 2nd level lists

def chunk_items(l, n):
    for sub_l in l:
        yield from chunks(sub_l, n)

Or if you're using python<3.3

def chunk_items(l, n):
    for sub_l in l:
        for x in chunks(sub_l, n):
            yield x

These return a generator, but if you really wanted to turn it into a list.

new_list = [x for x in chunk_items(lst, 3)]

EDIT:

Just saw in your question that you only wanted to chunk in sets of 3 if the length of the sublists were greater than 5, here's how you could modify the chunker to do that.

def chunk_items(l, n=3, m=5):
    for sub_l in l:
        if len(sub_l) > m:
            yield from chunks(sub_l, n)
        else:
            yield sub_l
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118