题目:
# 给定一个数组nums,编写一个函数将0移动到数组的末尾,同时保持非零元素的相对顺序。 # 输入:[1,3,0,12,5,0,7] # 输出:[1,3,12,5,7,0,0]
源代码:
def moveZeroes(nums): for i in range(nums.count(0)): nums.remove(0) #从列表中找到等于“0”这个元素的值,并把它删除 nums.append(0) #向列表的末尾加入“0”这个值。 return nums print(moveZeroes([1,3,0,12,5,0,7]))
运行结果: