I have something like this:
myList = [[1, None, None, None, None],[2, None, None, None, None],[3, 4, None, None, None]]
And if any of the lists in the list have 4 Nones, I want to remove them so the output is:
myList = [[3, 4, None, None, None]]
I tried using:
for l in myList:
if(l.count(None) == 4):
myList.remove(l)
But that consistently only removes half of them, even though I know the if statement is executing correctly resulting in this:
[[2, None, None, None, None], [3, 4, None, None, None]]
I managed to get it to work using this, but it can't be right:
for l in myList:
if(l.count(None) == 4):
del l[0]
del l[0]
del l[0]
del l[0]
del l[0]
myList = list(filter(None, myList))
What's a better way of doing this? Thanks in advance. I'm using python 3.3.
You could do it as:
my_new_list = [i for i in myList if i.count(None) < 4]
[OUTPUT]
[[3, 4, None, None, None]]
The problem is that you are modifying your list while iterating through it. If you want to use that kind of loop structure, do it as this instead:
i = 0
while i < len(myList):
if(myList[i].count(None) >= 4):
del myList[i]
else:
i += 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.