[英]Move Zeroes to the end of the string
I was just doing some leetcode but this blew my mind.我只是在做一些 leetcode 但这让我大吃一惊。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
nums = [0, 1, 0, 3 ,12]
k = 0
i=0
while i < len(nums):
print(i)
if nums[i] == 0:
print('inside if=',i)
print('before',nums)
k += 1
print('removed',nums[i])
nums.remove(i)
print('after',nums)
else:
i += 1
print('no change',nums)
print('final',nums)
for j in range (k):
nums.append(0)
print(nums)
and the output is:输出是:
0
inside if= 0
before [0, 1, 0, 3, 12]
element to be removed 0
after [1, 0, 3, 12]
0
no change [1, 0, 3, 12]
->1
->inside if= 1
->before [1, 0, 3, 12]
->element to be removed 0
->after [0, 3, 12]
1
no change [0, 3, 12]
2
no change [0, 3, 12]
final [0, 3, 12]
[0, 3, 12, 0, 0]
How can it remove element 1 if it can read that it has to remove 0?如果它可以读取它必须删除 0,它如何删除元素 1?
So I got to know my dumb mistake.所以我才知道我的愚蠢错误。 Actually
remove()
is used to remove the element that is mentioned.实际上
remove()
用于删除提到的元素。 Like if I type remove(6)
from a list a = [1,2,3,4,5,6]
.就像我从列表
a = [1,2,3,4,5,6]
键入remove(6)
一样。 it removes element 6, not the element that is at 6th position.它删除元素 6,而不是位于第 6 个位置的元素。 so use
pop()
to do so.所以使用
pop()
来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.