Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodically replacing values in a list

Tags:

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?

like image 646
Riley Avatar asked Sep 25 '18 08:09

Riley


People also ask

Does replace () work on lists?

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.

How do you replace multiple elements in a list in Python?

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.


1 Answers

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)) 
like image 140
Aran-Fey Avatar answered Dec 04 '22 21:12

Aran-Fey