简体   繁体   中英

How to split a list into groups of 4 where first elements are greater than the last?

I have this list of integers that I want to split into groups of 4 elements by condition:

result = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]

The first item of each group should be greater than the fourth following item. Output should be like this:

[[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]

but how do I apply that conditions in this code?

split_no = 4
list(split_list(result, split_no))

Currently my output looks like this:

[[0, 4, 10, 6], [15, 9, 18, 35], [40, -30, -90, 99]]

You could do the following

arr1 = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]
arr2=[arr1[x:x+4] for x in range(0, len(arr1)) if len(arr1[x:x+4])==4]
for each in arr2[:]:
    if each[0]<=each[3]:
        arr2.remove(each)

Now, if you try printing out arr2;

print(arr2)

you get:

[[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]

First, a list of all the sub-list of length 4 is created, using Python's list comprehension :

input_list = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]

all_sublists = [input_list[i:i+4] for i in range(len(input_list)-3)]

print(all_sublists)
# [[0, 4, 10, 6], [4, 10, 6, 15], [10, 6, 15, 9], [6, 15, 9, 18], [15, 9, 18, 35], [9, 18, 35, 40], [18, 35, 40, -30], [35, 40, -30, -90], [40, -30, -90, 99]]

Then, the sub-lists are filtered using the wanted conditions:

output = [sublist for sublist in all_sublists if sublist[0]>sublist[-1]]

print(output)
# [[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]

The one-line solution could be:

output = [input_list[i:i+4] for i in range(len(input_list)-3)
          if input_list[i]>input_list[i+3]]

print(output)
# [[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]

Answers from xdze2 and gireesh4manu have a drawback of keeping all subsequences of length 4 in memory. We can avoid that by using a rolling window iterator .

For example, taking one from this answer and improving it a bit:

from itertools import islice, tee

def windows(iterable, size): 
    iterators = tee(iterable, size) 
    iterators = [islice(iterator, i, None) for i, iterator in enumerate(iterators)]  
    yield from map(list, zip(*iterators))

def is_valid(seq):
    return seq[0] > seq[-1]

result = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]
print(list(filter(is_valid, windows(result, 4))))

will give you:

[[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -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