将零移动到列表末尾

时间:2019-08-28 17:02:14

标签: python list

我正在努力将所有零移动到列表末尾。 ..这种方法不好而且计算量大吗?

a = [1, 2, 0, 0, 0, 3, 6]
temp = []
zeros = []

for i in range(len(a)):
    if a[i] !=0:
        temp.append(a[i])
    else:
        zeros.append(a[i])

print(temp+zeros)

我的程序可以运行,但是不确定这是否是一种好方法吗?

10 个答案:

答案 0 :(得分:2)

这看起来像一个列表。您可以使用排序吗?

a = [1, 2, 0, 0, 0, 3, 6]
a.sort(reverse=True)
a

[6, 3, 2, 1, 0, 0, 0]

答案 1 :(得分:2)

一种避免更改其他元素顺序的sorted解决方案是:

from operator import not_

sorted(a, key=not_)

或未导入:

sorted(a, key=lambda x: not x)  # Or x == 0 for specific numeric test

通过将键简化为布尔值,sorted将其拆分为真实的事物,然后将其分解为虚假的事物,并且由于它是稳定的排序,因此每个类别中事物的顺序与原始事物相同输入。

答案 2 :(得分:1)

要将所有零移动到列表的末尾,同时保留所有元素在一次遍历中的顺序,我们可以从头开始保留所有非零元素的计数,并在出现a时将其与下一个元素交换在零之后遇到非零元素。 可以解释为:

<mets:mets LABEL="Moderní pedagogika, 2002" TYPE="Monograph"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:mets="http://www.loc.gov/METS/"
    xmlns:mods="http://www.loc.gov/mods/v3"
    xmlns:ns3="http://www.openarchives.org/OAI/2.0/oai_dc/"
    xmlns:ns5="http://www.w3.org/1999/xlink"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2001/XMLSchema.xsd http://www.loc.gov/METS/ http://www.loc.gov/standards/mets/mets.xsd http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-4.xsd http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd http://www.w3.org/1999/xlink http://www.w3.org/1999/xlink.xsd">
    <mets:metsHdr CREATEDATE="2012-12-05T07:42:22" LASTMODDATE="2012-12-05T07:42:22">
        <mets:agent ROLE="CREATOR" TYPE="ORGANIZATION">
            <mets:name>ABA001</mets:name>
        </mets:agent>
        <mets:agent ROLE="ARCHIVIST" TYPE="ORGANIZATION">
            <mets:name>ABA001</mets:name>
        </mets:agent>
    </mets:metsHdr>
    <mets:dmdSec ID="MODSMD_VOLUME_0001">
        .....   
    </mets:dmdSec>
    <mets:dmdSec ID="DCMD_VOLUME_0001"> 
        .....
    </mets:dmdSec>
</mets:mets>

循环的工作方式:

当i = 0时,arr [i]将为18,因此根据代码它将与自身交换,这没有区别,并且计数将增加1。当i = 1时,它将没有任何影响,因为到目前为止,我们遍历的列表是我们想要的(最后为零)。当i = 4时,arr [i] = 4且arr [count(1)] = 0,因此我们交换它们,将列表保留为[18,4,0,0,0,6],计数变为2,表示两个非-开头的零元素。然后循环继续。

答案 3 :(得分:0)

您的方法没有错,实际上取决于您要如何存储结果值。这是一种使用list.extend()list.count()的方法,该方法可以保留非零元素的顺序并生成单个列表。

a = [1, 2, 0, 0, 0, 3, 6]

result = [n for n in a if n != 0]
result.extend([0] * a.count(0))
print(result)
# [1, 2, 3, 6, 0, 0, 0]

答案 4 :(得分:0)

您的解决方案没有什么问题,如果您需要照顾一个聪明的解决方案,那么您应该始终选择一种您了解的解决方案。

这里是一个替代方案,它从不创建新列表,而仅通过列表一次。它还将保留项目的顺序。如果不必要的话,反向排序解决方案会更好。

def zeros_to_the_back(values):
    zeros = 0
    for value in values:
        if value == 0:
            zeros += 1
        else:
            yield value

    yield from (0 for _ in range(zeros))

print(list(
    zeros_to_the_back([1, 2, 0, 0, 0, 3, 6])
))

# [1, 2, 3, 6, 0, 0, 0]

这可以使用生成器工作,该生成器一次吐出一个答案。如果我们发现一个好的值,我们会立即将其返回,否则我们只计算零,然后在末尾返回一堆。

yield from是特定于Python 3的,因此,如果您使用的是2,只需将其替换为一个循环,零遍地产生零即可。

答案 5 :(得分:0)

您可以尝试

a = [1, 2, 0, 0, 0, 3, 6]
x=[i for i in a if i!=0]
y=[i for i in a if i==0]
x.extend(y)
print(x)

答案 6 :(得分:0)

保留订单的Numpy解决方案

import numpy as np

a = np.asarray([1, 2, 0, 0, 0, 3, 6])
# mask is a boolean array that is True where a is equal to 0
mask = (a == 0)
# Take the subset of the array that are zeros
zeros = a[mask]
# Take the subset of the array that are NOT zeros
temp = a[~mask]
# Join the arrays
joint_array = np.concatenate([temp, zeros])

答案 7 :(得分:0)

我尝试使用sorted,类似于sort()。

            services.AddPredictionEnginePool<ImageInputData, ImageLabelPredictions>();
            services.AddOptions<PredictionEnginePoolOptions<ImageInputData, ImageLabelPredictions>>()
                .Configure(options =>
                {
                    options.ModelLoader = new InMemoryModelLoader(_mlnetModel);
                });
a = [1, 2, 0, 0, 0, 3, 6]
sorted(a,reverse=True)

答案 8 :(得分:0)

named volume

因为我们必须保持相对顺序。当您看到非零元素时,将该非零元素放入 jth 的索引中。

from typing import List
def move(A:List[int]):
    j=0 # track of nonzero elements
    k=-1 # track of zeroes
    size=len(A)
    for i in range(size):
        if A[i]!=0:
            A[j]=A[i]
            j+=1
        elif A[i]==0:
            A[k]=0
            k-=1

使用 k 我们跟踪 0 个元素。在python中A[-1]指的是数组的最后一个元素。

first_nonzero=A[0]  # j=0
second_nonzero=A[1] # j=1
third_nonzero=A[2]  # j=2

答案 9 :(得分:0)

喜欢的可以试试我的方案

 Stack(
    alignment: Alignment.center,
    children: <Widget>[
      SizedBox(
        width: widget.width,
        height: widget.height,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(radius),
          child: Container(
            child: Material(
              color: Color(0xff0D8EEB),  
              child: InkWell(
                splashColor: Colors.white,
                onTap: () {
                   
                },
                child: SizedBox(
                    width: widget.width,
                    height: widget.height,
                    child:
                        FittedBox(fit: BoxFit.contain, child: widget.icon)),
              ),
            ),
          ),
        ),
      )
    ],
  ),

我已经在 leetcode 中尝试过这个代码,我的提交使用上面的代码被接受了。