简体   繁体   English

将列表从“ 0”拆分为两个列表

[英]Split list at '0' into two lists

I have a list: 我有一个清单:

matrix = [1, 2, 3, 0, 4, 5, 0, 6]

which needs to be split into a random amount of lists at 0 (ignoring 0): 需要将其拆分为0个随机列表(忽略0):

matrix1 = [3, 2, 1]
matrix2 = [4, 5]
matrix3 = [6]

How would I go about doing this? 我将如何去做呢? The original list will be of random length and with random numbers. 原始列表将具有随机长度且具有随机数。

One option is to use groupby : 一种选择是使用groupby

from itertools import groupby

lst = [1, 2, 3, 0, 4, 5, 0, 6]
[list(g) for k, g in groupby(lst, lambda x: x != 0) if k]
# [[1, 2, 3], [4, 5], [6]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM