python-3.x - 有没有办法在 Python3 中将列表分组为子列表?
问题描述
考虑以下:
some_list = [1, 2, 3, 4, 5, 9, 10]
如何通过不超过 1 的差异轻松地将这些整数分组?
final_list = [[1,2,3,4,5], [9, 10]]
我假设我需要使用 for 循环,并遍历原始列表,我只是有点不确定需要发生的逻辑。在此先感谢所有提供帮助的人!
final_list = []
group = []
init_position = some_list[0]
for i in some_list:
if(i - init_position > 1):
# re initialize group to empty here?
else:
group.append(i)
init_position = i
# Where do I append group to final_list now?
解决方案
您可以只引用group[-1]
而不是为列表中的最新项目保留变量。
def group_by_runs(sequence):
# set up lists
output = []
group = []
for elem in sequence:
# if the group has any items in it,
# and the last item is more than 1 removed from elem
if group and elem - group[-1] > 1:
# push the group to the output
output.append(group)
# reset the group
group = []
# add the next item to the group
group.append(elem)
# guard so we don't return an empty run
if group:
output.append(group)
return output
推荐阅读
- angular - 使用管道进行角度变化检测
- python - 具有多个用户类的 Flask-Login
- python - PYTHON - 如何从动态生成数据的 MarketWatch.com 中抓取库存“关键数据”。查找数据请求调用?
- database - 如何使用“不在列表中”填充查找表
- jq - 使用 jq,选择多个键并以数组的形式返回它们
- c# - 用于动态布局的 C# (MVC) 和 Bootstrap
- sql - 如何为列中的一组客户创建 1 个 ID?
- javascript - 如何将数组中的每个元素与一个值进行比较?
- python - 在数据流上运行 Apache Beam 管道会引发错误(DirectRunner 运行没有问题)
- php - Symfony 4 - FatalErrorException,错误:超过 30 秒的最大执行时间