简体   繁体   中英

how to split a list in python based on the values of the list

I have a list having sublists of numbers and want to extract specific ones. In my simplified example I have two main sublists and each one has its own pairs of numbers:

data=[[[1, 0], [2, 0], [2, 1], [2, 2],\
       [1, 0], [1, 1], [1, 2],\
       [0, 1], [0, 2], [0, 3]],\
      [[1, 0], [2, 0],\
       [1, 0],\
       [0, 1], [0, 2], [1, 2],\
       [1, 0], [1, 1], [1, 1]]]

Pairs stored in data can be divided based on some rules and I want the last pair of each division. For simplicity I have shown each division as a row in data . Each division starts with [1, 0] or [0, 1] and these two pairs are break points. Then, simply I want the last pair before each break points. In cases I may have no point between two break points and I only export the previous break point. Finally I want it as the following list:

data=[[[2, 2],\
       [1, 2],\
       [0, 3]],\
      [[2, 0],\
       [1, 0],\
       [1, 2],\
       [1, 1]]]
data=[[[1, 0], [2, 0], [2, 1], [2, 2],
   [1, 0], [1, 1], [1, 2],
   [0, 1], [0, 2], [0, 3]],
  [[1, 0], [2, 0],
   [1, 0],
   [0, 1], [0, 2], [1, 2],
   [1, 0], [1, 1], [1, 1]]]
newData = []

for subarray in data:
    new_subarray = []
    for i,item in enumerate(subarray):
        if item == [0,1] or item == [1,0]:
            if i> 0:
                new_subarray.append(subarray[i-1])
        if i == len(subarray)-1:
            new_subarray.append(item)
    newData.append(new_subarray)

print(newData)

You can do the following, using enumerate :

def fun(lst):
    return [p for i, p in enumerate(lst) if i==len(lst)-1 or set(lst[i+1])=={0,1}]
 
[*map(fun, data)]
# [[[2, 2], [1, 2], [0, 3]], [[2, 0], [1, 0], [1, 2], [1, 1]]]

fun filters a nested list for all elements that are either last or succeeded by [0, 1] or [1, 0] .

Here is a fun little unreadable numpy oneliner:

import numpy as np
[np.array(a)[np.roll(np.flatnonzero(np.logical_or(np.all(np.array(a)==(1, 0), axis=1), np.all(np.array(a)==(0, 1), axis=1)))-1, -1)].tolist() for a in data]

# [[[2, 2], [1, 2], [0, 3]], [[2, 0], [1, 0], [1, 2], [1, 1]]]

It works but in reality you'd better use schwobaseggl 's solution.

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