![](/img/trans.png)
[英]I want to remove all the numbers in a list less than 80 and move them into another list
[英]i want to remove all zero from one list and append all of them to another list but not all of them remove
我想從一個列表中刪除所有零,並將它們附加到另一列表中,但是當一個以上的零彼此接連出現時,其中一個不會刪除。
zero=[]
l=[2,3,6,0,0,5,6,0,7]
for i in l:
if i==0:
l.remove(i)
zero.append(i)
print(l)
print(zero)
l=[2, 3, 6, 5, 6, 0, 7]
zer0=[0, 0]
在此輸出中,零之一不刪除
迭代對象時不要修改列表。 相反,您可以使用副本。 l[:]
例如:
zero=[]
l=[2,3,6,0,0,5,6,0,7]
for i in l[:]:
if i==0:
l.remove(i)
zero.append(i)
print(l)
print(zero)
您正在遍歷正在修改的列表。 如果從該列表中刪除當前元素,它將縮小並且next(l)
將跳過一個元素。 為了避免這種情況,請始終遍歷列表的副本。 例如list(l)
或l[:]
。
zero=[]
l=[2,3,6,0,0,5,6,0,7]
for i in list(l):
if i==0:
l.remove(i)
zero.append(i)
print(l)
print(zero)
使用itertools.groupby
:
from itertools import groupby
l=[2,3,6,0,0,5,6,0,7]
non_zeros = []
zeros = []
for v, g in groupby(l, lambda k: k==0):
if v:
zeros.extend(g)
else:
non_zeros.extend(g)
print(non_zeros)
print(zeros)
印刷品:
[2, 3, 6, 5, 6, 7]
[0, 0, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.