Python的列表理解:如果出现某个值,则修改列表元素 [英] Python's list comprehension: Modify list elements if a certain value occurs

查看:265
本文介绍了Python的列表理解:如果出现某个值,则修改列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python的列表理解中执行以下操作?

How can I do the following in Python's list comprehension?

nums = [1,1,0,1,1]
oFlag = 1
res = []
for x in nums:
    if x == 0:
        oFlag = 0
    res.append(oFlag)
print(res)

# Output: [1,1,0,0,0]

本质上,在此示例中,一旦出现0,将列表的其余部分清零.

Essentially in this example, zero out the rest of the list once a 0 occurs.

推荐答案

nums = [1,1,0,1,1]
[int(all(nums[:i+1])) for i in range(len(nums))]

这将遍历整个列表,直到整个点为止都将all运算符应用于整个子列表.

This steps through the list, applying the all operator to the entire sub-list up to that point.

输出:

[1, 1, 0, 0, 0]

当然可以,这是 O(n ^ 2),但是可以完成工作.

Granted, this is O(n^2), but it gets the job done.

更有效的方法是简单地找到前0个索引. 制作一个由这么多1组成的新列表,并用适当数量的零填充.

Even more effective is simply to find the index of the first 0. Make a new list made of that many 1s, padded with the appropriate quantity of zeros.

if 0 in nums:
    idx = nums.index(0)
    new_list = [1] * idx + [0] * (len(nums) - idx)

...或者如果原始列表可以包含0和1以外的其他元素,则复制该列表,而不要重复1 s:

... or if the original list can contain elements other than 0 and 1, copy the list that far rather than repeating 1s:

    new_list = nums[:idx] + [0] * (len(nums) - idx)

这篇关于Python的列表理解:如果出现某个值,则修改列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆