在Python的列表中创建列表 [英] Creating a list within a list in Python

查看:71
本文介绍了在Python的列表中创建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为value的列表,其中包含一系列数字:

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]

我想创建一个新列表,其中包含从0到数字的元素列表.

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

赞:

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

我做的代码是这样的:

start = 0
new_values = []
for i,val in enumerate(values): 
    if(val == 0):
        new_values.append(values[start:i]) 
        start = i

但是,它返回什么:

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

如何修复我的代码?确实会有很大的帮助.

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

推荐答案

您可以根据0的存在将元素与itertools.groupby分组(很虚假),并在0之间提取子列表,同时附加缺少0且具有列表理解:

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]

示例:

>>> 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]]

这篇关于在Python的列表中创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆