Python 制作 list

标签 python arrays list for-loop iteration

我是Python方面的 super 高手。 我一直在努力寻找适当的解决方案。 这是列表,L = [0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 11, 12, 13, 14, 0, 0, 0, 18, 19 , 20],每个项目都引用列表中的位置。

我想从上面的列表开始创建列表,在列表内显示较小的列表,每个元素代表系列的起始位置、系列的结尾和元素的数量。这应该是[[3,6,4],[11,14,4],[18,20,3]]。我该如何为此编写代码?以下是我到目前为止所做的事情。

target = []
target.append([])
target.append([])
target.append([])

L = [0,0,0,0,4,5,6,7,8,9,0,0,0,13,14,15,0,0,0,19,20,21]

for i in L :
    if i == 0 :
        L.remove(i)
        continue
    elif i != 0 :
        startpoint = i
        i = i * i
        while i != 0 :
            i += 1
            continue
        else :
            j = i
            endpoint = i - 1
            break
    target[0].append(startpoint)
    target[1].append(endpoint)
    target[2].append(j)

最佳答案

关于您的代码,一个错误是在以下 while 中:

while i != 0 :
        i += 1

你不能增加i,你需要增加元素的索引而不是它本身!然后当你找到非零元素时继续追加!

但是作为一种更Pythonic的方式,您可以将itertools.groupby与列表理解一起使用:

>>> from itertools import groupby
>>> [[i[0],i[-1],len(i)] for i in [list(g) for _,g in groupby(L,key=lambda x:x!=0)]if i[0]!=0]
[[3, 6, 4], [11, 14, 4], [18, 20, 3]]

请注意groupby 将分组元素作为生成器 (g) 返回,当您想要循环它时,您不需要转换它到 list 但在这种情况下,因为我们需要长度,所以我们必须转换为 list 直到我们可以使用 len 函数。

关于Python 制作 list ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29982902/

相关文章:

python - QPushButton 选项卡高亮信号

list - 喜欢 first 和 rest 而不是 car 和 cdr 的 lisp 如何接近像 cdaddr 这样的组合?

python - 二维数组中索引对之间的总和

python - Django 静态 css 未加载?

python - pandas 乘法中的 Groupby

c - 当我溢出分配的字符数组时,为什么我的 C 程序不会崩溃?

c++ - 如何在数组中找到特定值并返回其索引?

javascript - Google 电子表格脚本 - 仅授予对一张工作表的访问权限

django 管理员截断 list_display 中的文本

mysql - 从存储在(Mysql 表)中的项目生成列表