我正在学习算法,有一个问题:
Given an array of integers, pack consecutive elements into sublists.
For example, given the list [4, 4, 1, 6, 6, 6, 1, 1, 1, 1], return [[4, 4], [1], [6, 6, 6], [1, 1, 1, 1]].
Note: If there's only one occurrence in the list it should still be in its own sublist.
我创建了以下解决方案:
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]]
它正在工作,但正如你所看到的,它不是很干净。我该如何改进这一点
试试这个:
new_list
将是您预期的结果您可以尝试^{} :
另一种方法是:
相关问题 更多 >
编程相关推荐