创建列表python_在Python的列表中创建列表

I have a list named values containing a series of numbers:

values = [0, 1, 2, 3, 4, 5, ... , 351, 0, 1, 2, 3, 4, 5, 6, ... , 750, 0, 1, 2, 3, 4, 5, ... , 559]

I want to create a new list that contains a list of elements from 0 up to a number.

Like :

new_values = [[0, 1, 2, ... , 351], [0, 1, 2, ... , 750], [0, 1, 2, ... , 559]]

The code that I did was this:

start = 0

new_values = []

for i,val in enumerate(values):

if(val == 0):

new_values.append(values[start:i])

start = i

However, what it returns this:

new_values = [[], [0, 1, 2, ... , 750], [0, 1, 2, ... , 559]]

How can I fix my code? It will really be a great help.

解决方案

You can group your elements with itertools.groupby based on the presence of 0 (which is falsy) and extract the sublists between 0 while appending the missing 0 with a list comprehension:

[[0]+list(g) for k, g in groupby(values, bool) if k]

Example:

>>> from itertools import groupby

>>> values = [0, 1, 2, 3, 4, 5 , 351, 0, 1, 2, 3, 4, 5, 6, 750, 0, 1, 2, 3, 4, 559]

>>> [[0]+list(g) for k, g in groupby(values, bool) if k]

[[0, 1, 2, 3, 4, 5, 351], [0, 1, 2, 3, 4, 5, 6, 750], [0, 1, 2, 3, 4, 559]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值