如何删除在此循环中弹出的值为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)
答案 0 :(得分:2)
你总是可以使用列表理解来过滤它们:
for i in range(len(y)):
y[i] -= 1
y = [x for x in y if x != 0] # <-- added here
y.append(len(y))
修改强>:
我很傻 - 这些操作甚至可以这样组合:
while whatever: #<-- fix as suggested by comment on your question
y = [z-1 for z in y if z > 1]
y.append(len(y))
答案 1 :(得分:1)
y = filter(lambda i: i != 0, y)