简体   繁体   English

从列表中删除元素

[英]removing elements from a list

How can i remove elements with a value of 0 as they pop upp in this loop?当它们在此循环中弹出时,如何删除值为 0 的元素?

y = [4, 2, 7, 9]
x = input("run?")
while x:
    for i in range(len(y)):
        y[i] -= 1
    y.append(len(y))
    print(y)

you could always use a list comprehension to filter them:你总是可以使用列表推导来过滤它们:

for i in range(len(y)):
    y[i] -= 1
y = [x for x in y if x != 0]  # <-- added here
y.append(len(y))

EDIT :编辑

I'm silly - these operations could even be combined as so:我很傻 - 这些操作甚至可以这样组合:

while whatever: #<-- fix as suggested by comment on your question
    y = [z-1 for z in y if z > 1]
    y.append(len(y))
y = filter(lambda i: i != 0, y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM