python - 将相似的项目打包到列表中
问题描述
我正在学习算法,并且出现了这个问题:
给定一个整数数组,将连续元素打包到子列表中。
例如,给定列表 [4, 4, 1, 6, 6, 6, 1, 1, 1, 1],返回 [[4, 4], [1], [6, 6, 6], [1 , 1, 1, 1]]。
注意:如果列表中只有一次出现,则它仍应位于其自己的子列表中。
我创建了以下解决方案:
def solve(nums):
packed = []
lastElement = nums[0]
currPack = []
for i, num in enumerate(nums):
newPack = []
if lastElement == num:
currPack.append(num)
else:
newPack.append(num)
packed.append(currPack)
currPack = newPack
lastElement = num
packed.append(currPack)
return packed
nums = [4,4,1,6,6,6,1,1,1,1]
solve(nums)
# [[4,4], [1], [6,6,6], [1,1,1,1]]
它正在工作,但正如您所见,它不是很干净。我该如何改进呢?
解决方案
你可以试试itertools.groupby
:
>>> from itertools import groupby
>>> x = [4, 4, 1, 6, 6, 6, 1, 1, 1, 1]
>>> new_list = [list(group) for _, group in groupby(x)]
>>> new_list
[[4, 4], [1], [6, 6, 6], [1, 1, 1, 1]]
>>>
另一种方法是:
>>> master_list, new_list = [], []
>>> for elem in x:
... if not new_list:
... new_list.append(elem)
... elif elem == new_list[-1]:
... new_list.append(elem)
... else:
... master_list.append(new_list)
... new_list = [elem]
>>> master_list.append(new_list)
>>> master_list
[[4, 4], [1], [6, 6, 6], [1, 1, 1, 1]]
推荐阅读
- regex - 是否可以为 Notepad++ 正则表达式指定 Unicode 类别类?
- c# - 通过 csv/txt 将数据(SQL Server 表)分发给第三方的方式 - 在用户输入后由 WHERE 子句过滤
- python - 在 Python 中修补嵌套对象
- string - PowerShell,管道兼容的 Select-String 函数
- sublimetext3 - 以日期和时间为自定义变量的 Sublime Text 3 片段
- sql - MERGE 语句在 Informix v10 中不起作用
- python - 使用 pip 命令将 matplotlib 和 Getfem 安装到 Python 3.9.0 时出错
- python - multiprocessing.Pool 无限循环(并行处理不停止)
- java - traefik https 给出 404 错误,即使我的安全端口配置正确,http 也能正常工作
- javascript - 我想通过聊天设置角色 | 不和谐.js v12