Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中删除元素_Python - Fatal编程技术网

Python 从列表中删除元素

Python 从列表中删除元素,python,Python,在循环中弹出upp时,如何删除值为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) 您可以始终使用列表理解来筛选它们: for i in range(len(y)): y[i] -= 1 y = [x for x in y if x != 0] # <-- added he

在循环中弹出upp时,如何删除值为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)

您可以始终使用列表理解来筛选它们:

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

y=[x代表x,如果x!=0]#
而如果
x
的计算结果为
True
则x
将使您进入无限循环。注意-过滤器+lambda通常被认为比列表理解慢;你可能会对它感兴趣。
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)