不确定如何在循环中使用列表理解

2024-05-13 23:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我从未使用过列表理解法,但在过去的几个小时里,我一直在尝试将我读到的内容应用到我正在研究的方法中。我很难把我所看到的例子应用到我的案件中去。你知道吗

给定一个列表,创建一个大小相等的新列表。在新列表中,将所有数字向左移动,将零向右移动。例如,[0,3,0,4]将返回[3,4,0,0]。我的工作方法是:

def merge(self, line):
    results = [0] * len(line)
    count = 0
    for number in line:
        if number != 0:
            results[count] = number
            count += 1
    return results

每次我尝试压缩它时,我都会被如何在没有索引的情况下完成results[count] = number所困扰。你知道吗


Tags: 方法selfnumber内容列表lendefcount
3条回答

尝试:

l = [0, 3, 0, 4]
nl = [ x for x in l if x != 0]
print nl.extend([0] * (len(l) - len(nl))

请尝试以下操作:

def merge(self, line):
    return [item for item in line if item != 0]+[0 for item in line if item == 0]

其运行方式为:

>>> merge([0, 3, 0, 4])
[3, 4, 0, 0]
>>> 

你可以做:

def merge(self, line):
    return ([x for x in line if x] + ([0] * len(line)))[:len(line)]

这将从line中获取非零项,然后用零填充,切片以确保适当的长度。你知道吗

由于您不使用任何类或实例参数,因此可以将其设为静态方法以删除不必要的参数:

@staticmethod
def merge(line):
    return ([x for x in line if x] + ([0] * len(line)))[:len(line)]

但是,请注意,您当前的版本是清晰的、可读的,并且比这个版本的内存效率更高(它构建了两个列表,添加它们以生成第三个列表,然后切掉第四个列表)。你知道吗

相关问题 更多 >