首页 > 解决方案 > 从具有重复值的列表中理解嵌套列表

问题描述

要得到[[1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

来自 old_list =[1,1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

我找到了这个答案:

new_list = []
for value in old_list:
    if new_list and new_list[-1][0] == value:
        new_list[-1].append(value)
    else:
        new_list.append([value])

我试图理解 new_list[-1][0] 的含义是什么,当我尝试运行时出现了混淆

new_list = []
new_list[-1] # shows index out of bounds

并且new_list and new_list[-1][0]在 if 语句下不会产生任何错误

new_list[-1][0]在这里做什么。

标签: pythonlist

解决方案


new_list[-1][0]检索 的最后一个元素new_list,它本身就是一个列表并获取它的第一个元素。

new_list and new_list[-1][0] == value短路,因此如果列表为空,它不会尝试访问最后一个元素。


推荐阅读