繁体   English   中英

迭代 Python 列表列表并删除每个子列表的最终索引,无导入

[英]Iterate Python List of Lists and Remove Final Index of Each Sublist, No Imports

有一些与此类似的问题,但不完全相同:

我想动态减少给定的输入数组或列表列表。 例如:

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

从 0 开始,我需要遍历并删除最终索引 - 迭代。 所以我想存储在新列表中的输出是:

#output
[0,1,2], ,[3,4], [6]] 
[0,1,2], ,[3,4], [6]] ==> which then flattens to [0,1,2,3,4,6]

这是我目前正在追求的:

def get_list(matrix, stop_index):
    temp = [] 

    for i in range(0, stop_index):
        for m in matrix:
            temp.append(matrix[0:stop_index])
        outside_list.append(temp)

    return outside_list

我相信我很清楚我对包和库的过度依赖,所以我真的试图在没有外部包或导入的情况下做到这一点

感谢您的任何帮助! 我不会忘记绿色复选标记。

使用列表理解

l = [[0,1,2], [3,4,5],[6,7,8]]
ll = [ x[:len(l)-l.index(x)] for x in l]
# [[0, 1, 2], [3, 4], [6]]
print([x for y in ll for x in y ])
# [0, 1, 2, 3, 4, 6]

更简单的语法:

    matrix = [[0,1,2], [3,4,5],[6,7,8]]
    outside_list = list()
    for i in range(len(matrix)):
        # matrix[i] is used to access very sublist in the matrix, 
        #[:3-i] is to slice every sublist from the beginning to (3 - current position)
        outside_list.append(matrix[i][:3-i])
    print(outside_list)

一些有用的参考

暂无
暂无

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

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