【问题标题】:Unable to move 0's to the end of list properly Python无法将 0 正确移动到列表末尾 Python
【发布时间】:2018-05-22 15:16:40
【问题描述】:

所以这里的目标是将所有 0 移到数组的末尾,但我从这些小代码行中偶然发现了一个问题。

当我使用输入时,我会得到所需的输出,如下所示:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

但是,每当我使用此输入时:

[0,0,1]

我得到这个输出:

[0,1,0]

当我想要输出时:

[1,0,0]

我不知道为什么我认为我正确地实现了这个:

class Solution:
def moveZeroes(self, nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    for counter in range(len(nums)):
        if nums[counter] == 0:
            nums.pop(counter) #Remove the 0
            nums.append(0) #Add to end. 
            counter-=1 #Check same index just incase adjacent 0

感谢任何输入。谢谢!

【问题讨论】:

  • 有一种更简单的方法:x = [1,5,6,0,4],而不是对您的列表进行排序:x.sort(reverse = True)
  • @J.A.Cado 这不是一回事。它将对所有值进行排序,而不仅仅是将零分流到末尾。

标签: python


【解决方案1】:

我什至不会打扰手动 for 循环...

def move_zeroes(nums):
    nums[:] = [n for n in nums if n != 0] + [0] * nums.count(0)

x = [0,1,0,3,12]
move_zeroes(x)
print(x)

输出

[1, 3, 12, 0, 0]

【讨论】:

  • [n for n in nums if n] 更短:)
  • @Jean-FrançoisFabre 当然,如果您相信列表中的所有内容都是数字 ;)
  • 我什至没有接近这个解决方案。谢谢!
【解决方案2】:

for 循环不等同于具有增量的while 循环。您的最后一行 counter-=1 没有实现任何效果:在您减少 counter 后,它立即采用该范围内的下一个值。 (需要明确的是,例如,如果您在迭代 counter = 2 中,那么无论您在本次迭代结束时将 counter 留下什么值,它都会在下一次迭代时重新分配给 3。)

【讨论】:

    【解决方案3】:

    这一行:

    counter-=1 #Check same index just incase adjacent 0
    

    不会降低以下索引的索引。

    试试这个:

    class Solution:
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            zeros_found = 0
            for counter in range(len(nums)):
                idx = counter - zeros_found
                if nums[idx] == 0:
                    nums.pop(idx) #Remove the 0
                    nums.append(0) #Add to end. 
                    zeros_found += 1 #Account for offset
    

    您还可以更实用地执行此操作:

    from itertools import filterfalse
    # ...
    def moveZeroes(self, nums):
        none_zeroes = list(filter(None, nums))
        zeros = list(filterfalse(None, nums))
        return none_zeros + zeros
    

    或者如果您无缘无故不想创建列表:

    from itertools import filterfalse, chain
    # ...
    def moveZeroes(self, nums):
        none_zeroes = filter(None, nums)
        zeros = filterfalse(None, nums)
        return list(chain(none_zeros, zeros))
    

    这些依赖于两个隐含的事实:

    1. bool(0) 是 False,当 x != 0 是 True 时,bool(x)
    2. filter(None, list) 按项目的 bool 值过滤列表,因此没有 0(与 filterfalse 相反)

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 1970-01-01
      • 2021-10-01
      • 2023-03-17
      • 2017-07-10
      • 2019-04-06
      • 2020-06-09
      • 2011-06-22
      • 1970-01-01
      相关资源
      最近更新 更多