I have a list like this:
my_list=[False, False, True, True, False, False, True]
I want to change this list so that the first n occurrence of True remain in place and all others became False.
for example, if n=1, I want to create a new list same as this one:
my_new_list=[False, False, True, False, False, False, False]
and if n=2; this list should be created:
my_new_list=[False, False, True, True, False, False, False]
I can do this in a for loop easily, but what is the best way of doing this in Python?
Edit1
This is my code:
def f(l,n):
c=1
new_l=[False] * len(l)
if n>= len(l):
return new_l
for i,v in enumerate(l):
if v:
if(c >= n):
return new_l
new_l[i]=True
c =1
return new_l
This code goes over all the items of the list, but a portion of it. But it has 9 lines of code, is there any shorter version or a faster version?
CodePudding user response:
With a list comp:
my_new_list = [x and (n := n - 1) >= 0 for x in my_list]
CodePudding user response:
You could use accumulate (from itertools) to count how many True values you have so far and match it to the value of n
:
my_list=[False, False, True, True, False, False, True]
from itertools import accumulate
n = 1
r = [isTrue and count<=n for isTrue,count in zip(my_list,accumulate(my_list))]
print(r)
[False, False, True, False, False, False, False]
n = 2
r = [isTrue and count<=n for isTrue,count in zip(my_list,accumulate(my_list))]
print(r)
[False, False, True, True, False, False, False]
using numpy
The same approach can be used more concisely with numpy:
import numpy as np
my_list=[False, False, True, True, False, False, True]
n=1
r = my_list & (np.cumsum(my_list)<=n)
print(r)
# [False False True False False False False]
n=2
r = my_list & (np.cumsum(my_list)<=n)
print(r)
# [False False True True False False False]
CodePudding user response:
def function(l,n):
new_list = []
c = 0
for i in l:
if not i:
new_list.append(False)
else:
if c < n:
new_list.append(False)
c =1
else:
new_list.append(True)
return new_list
OR:
def function(l,n):
return [False if (not i) or (n := n-1) >= 0 else True for i in l]