Change language

# Python | Split a list into lists by a specific value

|

Method: Using list comprehension + ` zip () + slicing + enumerate () `

This problem can be solved in two parts, in the first part, we get a list of indices by which we need to split using the enumeration function. And then we can concatenate the values ​​according to indices using zip and list slicing.

 ` # Python3 demo code ` ` # Split the list into lists by specific value ` ` # Using comprehension list + zip () + slicing + enumerate () `   ` # initializing list ` ` test_list ` ` = ` ` [` ` 1 ` `, ` ` 4 ` `, ` ` 5 ` `, ` ` 6 ` `, ` ` 4 ` `, ` ` 5 ` `, ` ` 6 ` `, ` ` 5 ` `, ` ` 4 ` `] `   ` # print original list ` ` print ` ` (` ` "The original list:" ` ` + ` ` str ` ` (test_list)) `   ` # use comprehension list + zip () + slicing + enumerate () ` ` # Split list into lists by specific value ` ` size ` ` = ` ` len ` ` (test_list) ` ` idx_list ` ` = ` ` [idx ` ` + ` ` 1 ` ` for ` ` idx, val ` ` in ` ` enumerate ` ` (test_list) ` ` if ` ` val ` ` = ` ` = ` ` 5 ` `] `     ` res ` ` = ` ` [test_list [i: j] ` ` for ` ` i, j ` ` in ` ` zip ` ` ([` ` 0 ` `] ` ` + ` ` idx_list, idx_list ` ` + `  ` ([ size] ` ` if ` ` idx_list [` ` - ` ` 1 ` `]! ` ` = ` ` size ` ` else ` ` []))] `   ` # print result ` ` print ` ` (` ` "The list after splitting by a value:" ` ` + ` ` str ` ` (res)) `

Output:

` The original list: [1, 4, 5, 6, 4, 5, 6, 5, 4] The list after splitting by a value: [[1, 4, 5], [6 , 4, 5], [6, 5], [4]] `