[Solved] How to create a List of Lists based on certain value in a List in Python


VALUE = 32

p = [
     [84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 32, 111, 102, 32], 
     [9, 9, 73, 116, 32, 105, 115, 32, 98, 101, 97, 117, 116, 105, 102, 117, 108, 108, 121, 46], 
     [78, 101, 101, 100, 32, 116, 111, 32, 102, 105, 103, 117, 114, 101, 32, 108, 105, 110, 101, 46], 
     [105, 116, 32, 97, 110, 100, 32, 108, 111, 118, 105, 110, 103, 32, 105, 116, 46, 46, 46], 
     [49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 46, 46, 46, 33, 33, 33]
    ]

result = []
for pi in p:
    sublists = []
    start = 0
    try:
        while start < len(pi):
            idx = pi.index(VALUE, start)
            sublists.append(pi[start:idx + 1])
            start = idx + 1
    except ValueError:
        if start < len(pi):
            sublists.append(pi[start:])
    result.append(sublists)

print(result)
>>> [[[84, 104, 105, 115, 32], [105, 115, 32], [97, 32], [116, 101, 115, 116, 32], [111, 102, 32]], [[9, 9, 73, 116, 32], [105, 115, 32], [98, 101, 97, 117, 116, 105, 102, 117, 108, 108, 121, 46]], [[78, 101, 101, 100, 32], [116, 111, 32], [102, 105, 103, 117, 114, 101, 32], [108, 105, 110, 101, 46]], [[105, 116, 32], [97, 110, 100, 32], [108, 111, 118, 105, 110, 103, 32], [105, 116, 46, 46, 46]], [[49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 46, 46, 46, 33, 33, 33]]]

6

solved How to create a List of Lists based on certain value in a List in Python