python - 从具有重复值的列表中理解嵌套列表
问题描述
要得到[[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]
在这里做什么。
解决方案
new_list[-1][0]
检索 的最后一个元素new_list
,它本身就是一个列表并获取它的第一个元素。
new_list and new_list[-1][0] == value
短路,因此如果列表为空,它不会尝试访问最后一个元素。
推荐阅读
- c# - 我们如何获得每月(星期几)用于备份目的
- c++ - 如何在 msvc 中编译和链接生成的文件?
- c++ - 为什么 j 的值为 11?
- python - 更改ttk笔记本的文字大小和颜色
- c++ - 存在 StyleSheet 时如何使用 Qt::BackgroundRole 更改背景颜色
- c# - 多个服务中的存储库对象
- google-cloud-platform - 创建一个基于日志的指标来跟踪 2 个日志之间的差异
- nginx - 如何在 Loadbalancer(Keepalived) & kubernetes APP Docker Container 中增加最大请求标头
- nlp - 不同的
kenlm 和 berkeleylm 之间的概率 - javascript - 如何在 amcharts4 中将时间戳 unix 格式化为日期