Python 中将相同连续元素打包到子列表中的程序
pythonserver side programmingprogramming更新于 2026/2/2 7:08:17
假设我们有一个数字列表 nums,我们将把相同值的连续元素打包到子列表中。我们必须记住,列表中只有一个出现,它仍然应该在它自己的子列表中。
因此,如果输入为 nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2],则输出将是 [[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]
为了解决这个问题,我们将遵循以下步骤 −
- 如果 nums 为空,则
- 返回一个新列表
- result := 一个列表,其中包含另一个包含 nums[0] 的列表
- j := 0
- 对于 i,范围从 1 到 nums 的大小,执行
- 如果 nums[i] 与 nums[i - 1] 不同,则
- 在结果末尾插入一个新列表
- j := j + 1
- 在 result[j] 末尾插入 nums[i]
- 如果 nums[i] 与 nums[i - 1] 不同,则
- 返回 result
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): if not nums: return [] result = [[nums[0]]] j = 0 for i in range(1, len(nums)): if nums[i] != nums[i - 1]: result.append([]) j += 1 result[j].append(nums[i]) return result ob = Solution() nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2] print(ob.solve(nums))
输入
[5, 5, 2, 7, 7, 7, 2, 2, 2, 2]
输出
[[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

