Suppose I have the following list in Python:
my_list = [10] * 95 Given n, I want to replace any other m elements with zero in my list, while keeping the next n elements.
For example, if n = 3 and m = 2, I want my list to look like:
[10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0] If it can't be filled perfectly, as is the case with n = 4 and m = 2, then it's OK if my list looks like this:
[10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0] How should I try to solve this problem?
You can replace items in a Python list using list indexing, a list comprehension, or a for loop. If you want to replace one value in a list, the indexing syntax is most appropriate.
Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
You could use itertools.cycle to create an endless sequence of [10, 10, 10, 0, 0] and then take the first 95 elements of that sequence with itertools.islice:
n = 3 m = 2 pattern = [10] * n + [0] * m my_list = list(itertools.islice(itertools.cycle(pattern), 95))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With