Periodically replacing values in a list
Clash Royale CLAN TAG#URR8PPP
up vote
20
down vote
favorite
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?
python list replace
 |Â
show 5 more comments
up vote
20
down vote
favorite
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?
python list replace
Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like[10, 10, 10, 0, 0, ...]
or do you want to overwrite every nth value in an existing list?
â Aran-Fey
Sep 25 at 8:13
6
How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
â Denny
Sep 25 at 11:15
1
@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
â Riley
Sep 25 at 11:22
3
Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
â user202729
Sep 25 at 13:08
3
It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
â user202729
Sep 25 at 15:17
 |Â
show 5 more comments
up vote
20
down vote
favorite
up vote
20
down vote
favorite
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?
python list replace
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?
python list replace
python list replace
edited Sep 25 at 8:08
Aran-Fey
20.4k53165
20.4k53165
asked Sep 25 at 8:00
Riley
280113
280113
Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like[10, 10, 10, 0, 0, ...]
or do you want to overwrite every nth value in an existing list?
â Aran-Fey
Sep 25 at 8:13
6
How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
â Denny
Sep 25 at 11:15
1
@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
â Riley
Sep 25 at 11:22
3
Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
â user202729
Sep 25 at 13:08
3
It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
â user202729
Sep 25 at 15:17
 |Â
show 5 more comments
Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like[10, 10, 10, 0, 0, ...]
or do you want to overwrite every nth value in an existing list?
â Aran-Fey
Sep 25 at 8:13
6
How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
â Denny
Sep 25 at 11:15
1
@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
â Riley
Sep 25 at 11:22
3
Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
â user202729
Sep 25 at 13:08
3
It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
â user202729
Sep 25 at 15:17
Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like
[10, 10, 10, 0, 0, ...]
or do you want to overwrite every nth value in an existing list?â Aran-Fey
Sep 25 at 8:13
Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like
[10, 10, 10, 0, 0, ...]
or do you want to overwrite every nth value in an existing list?â Aran-Fey
Sep 25 at 8:13
6
6
How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
â Denny
Sep 25 at 11:15
How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
â Denny
Sep 25 at 11:15
1
1
@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
â Riley
Sep 25 at 11:22
@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
â Riley
Sep 25 at 11:22
3
3
Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
â user202729
Sep 25 at 13:08
Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
â user202729
Sep 25 at 13:08
3
3
It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
â user202729
Sep 25 at 15:17
It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
â user202729
Sep 25 at 15:17
 |Â
show 5 more comments
8 Answers
8
active
oldest
votes
up vote
25
down vote
accepted
my_list = [10] * 95
n = 3
m = 2
for i in range(m):
my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])
This just needs m
assignments to do the job (and m
probably is small).
If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:
my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]
But that iterates in Python over the whole range of 95, so probably is not very fast.
A bit more complex but probably more efficient (especially for huge lists and large values for n
and m
) would be this:
my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]
But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)
If you can use numpy
(a bit off the question, but since it's widespread):
my_list = (np.arange(95) % (n+m) < n) * 10
Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
â Aran-Fey
Sep 25 at 8:43
3
@Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
â Alfe
Sep 25 at 10:47
add a comment |Â
up vote
27
down vote
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))
Why use itertools when you can use list expression?
â Moonsik Park
Sep 25 at 8:28
5
@MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
â Aran-Fey
Sep 25 at 8:29
add a comment |Â
up vote
7
down vote
Yet another possibility, this time with enumerate
:
[x * (i % (n + m) < n) for i, x in enumerate(my_list)]
It uses the fact that False
and True
are equal to 0
and 1
in Python (see here).
As a bonus, it works fine even if the list isn't constant:
>>> n = 4
>>> m = 2
>>> my_list = range(20)
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
[0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]
If the list contains strings, it replaces them with an empty string instead of 0
:
>>> my_list = 'abcdefghijk'
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']
add a comment |Â
up vote
6
down vote
This worked for me:
list = [10] * 95
n = 4
m = 2
amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]
list = np.asarray(list)*amask
which outputs:
array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0.])
The code takes n
and m
and constructs a mask of ones and zeros with a length matching your initial list
using the np.tile
function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n
and m
.
You can cast the array back to a list if you want.
1
numpy
? For real?
â Alfe
Sep 25 at 8:19
1
@Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
â Eric Duminil
Sep 25 at 9:51
@EricDuminil Just overkill for the job, that's all. It's like asking for aprint()
and getting af=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close()
. Works, yeah. But adds unnecessary complexity.
â Alfe
Sep 25 at 10:41
1
Btw, innumpy
, I would have done it as(np.arange(95) % 5 < 3) * 10
.
â Alfe
Sep 25 at 10:44
3
@Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
â Shintlor
Sep 25 at 12:19
 |Â
show 1 more comment
up vote
4
down vote
How about this?
my_list = [10] * 95
n = 3
m = 2
for i in range(n, len(my_list)-1, n+m):
my_list[i:i+m] = [0]*m
print(my_list)
Edit
I found out that the above code changes the length of resulting list in some cases.
>>> a = [1,2,3]
>>> a[2:4] = [0] * 2
>>> a
[1, 2, 0, 0]
Thus, the length should be restored somehow.
my_list = [10] * 95
cp_list = list(my_list)
n = 3
m = 5
for i in range(n, len(my_list)-1, n+m):
cp_list[i:i+m] = [0]*m
cp_list = cp_list[:len(my_list)]
print(cp_list)
1
Nice approach. But only iflen(my_list)
is smaller thanm
, this is more efficient than my solution.
â Alfe
Sep 25 at 8:24
1
There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
â Alfe
Sep 25 at 8:29
2
For deleting the last elements of a list, best usedel cp_list[n:]
.
â Alfe
Sep 25 at 14:58
add a comment |Â
up vote
3
down vote
numpy
can do this pretty concisely, too!
a = np.array(my_list).reshape(-1, n + m)
a[:, n:] = 0
result = a.ravel().tolist()
2
It doesn't seem to work withn = 4
andm = 2
. It raisesValueError: cannot reshape array of size 95 into shape (6)
.
â Eric Duminil
Sep 25 at 9:57
@EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
â timgeb
Sep 25 at 10:02
Please take a look at the second half of the question. This use case is specifically mentioned by OP.
â Eric Duminil
Sep 25 at 10:03
3
@EricDuminil you are right. This answer does not work in the latter case.
â timgeb
Sep 25 at 10:05
add a comment |Â
up vote
3
down vote
[j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
Maybe?
Result
>>> num, input_num, m, n=95, 10, 2, 3
>>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
[10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]
3
I guess the list full of10
is just for an example...
â Julien
Sep 25 at 8:07
@Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
â Moonsik Park
Sep 25 at 8:20
1
1) Your output is incorrect (it's[10, 10, 0, 0, 0]
instead of[10, 10, 10, 0, 0]
) 2) Concatenating lists withsum
is an antipattern with a massive run time complexity.
â Aran-Fey
Sep 25 at 8:34
@Aran-Fey Nope, it's correct.
â Moonsik Park
Sep 25 at 8:39
Oops. Indeed it is. Edited.
â Moonsik Park
Sep 25 at 8:44
add a comment |Â
up vote
0
down vote
Also in the itertools family, you can repeat
a desired pattern:
Given
import itertools as it
m, n = 2, 3
p = n + 1
Code
pattern = it.repeat([10] * n + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]
pattern = it.repeat([10] * p + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]
Test
assert len(res) == 95
However, @Aran-Fey's itertools.cycle
solution is cleaner as it does not require chaining.
add a comment |Â
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
25
down vote
accepted
my_list = [10] * 95
n = 3
m = 2
for i in range(m):
my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])
This just needs m
assignments to do the job (and m
probably is small).
If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:
my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]
But that iterates in Python over the whole range of 95, so probably is not very fast.
A bit more complex but probably more efficient (especially for huge lists and large values for n
and m
) would be this:
my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]
But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)
If you can use numpy
(a bit off the question, but since it's widespread):
my_list = (np.arange(95) % (n+m) < n) * 10
Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
â Aran-Fey
Sep 25 at 8:43
3
@Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
â Alfe
Sep 25 at 10:47
add a comment |Â
up vote
25
down vote
accepted
my_list = [10] * 95
n = 3
m = 2
for i in range(m):
my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])
This just needs m
assignments to do the job (and m
probably is small).
If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:
my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]
But that iterates in Python over the whole range of 95, so probably is not very fast.
A bit more complex but probably more efficient (especially for huge lists and large values for n
and m
) would be this:
my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]
But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)
If you can use numpy
(a bit off the question, but since it's widespread):
my_list = (np.arange(95) % (n+m) < n) * 10
Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
â Aran-Fey
Sep 25 at 8:43
3
@Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
â Alfe
Sep 25 at 10:47
add a comment |Â
up vote
25
down vote
accepted
up vote
25
down vote
accepted
my_list = [10] * 95
n = 3
m = 2
for i in range(m):
my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])
This just needs m
assignments to do the job (and m
probably is small).
If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:
my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]
But that iterates in Python over the whole range of 95, so probably is not very fast.
A bit more complex but probably more efficient (especially for huge lists and large values for n
and m
) would be this:
my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]
But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)
If you can use numpy
(a bit off the question, but since it's widespread):
my_list = (np.arange(95) % (n+m) < n) * 10
my_list = [10] * 95
n = 3
m = 2
for i in range(m):
my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])
This just needs m
assignments to do the job (and m
probably is small).
If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:
my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]
But that iterates in Python over the whole range of 95, so probably is not very fast.
A bit more complex but probably more efficient (especially for huge lists and large values for n
and m
) would be this:
my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]
But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)
If you can use numpy
(a bit off the question, but since it's widespread):
my_list = (np.arange(95) % (n+m) < n) * 10
edited Sep 25 at 10:45
answered Sep 25 at 8:22
Alfe
29.9k106098
29.9k106098
Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
â Aran-Fey
Sep 25 at 8:43
3
@Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
â Alfe
Sep 25 at 10:47
add a comment |Â
Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
â Aran-Fey
Sep 25 at 8:43
3
@Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
â Alfe
Sep 25 at 10:47
Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
â Aran-Fey
Sep 25 at 8:43
Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
â Aran-Fey
Sep 25 at 8:43
3
3
@Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
â Alfe
Sep 25 at 10:47
@Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
â Alfe
Sep 25 at 10:47
add a comment |Â
up vote
27
down vote
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))
Why use itertools when you can use list expression?
â Moonsik Park
Sep 25 at 8:28
5
@MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
â Aran-Fey
Sep 25 at 8:29
add a comment |Â
up vote
27
down vote
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))
Why use itertools when you can use list expression?
â Moonsik Park
Sep 25 at 8:28
5
@MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
â Aran-Fey
Sep 25 at 8:29
add a comment |Â
up vote
27
down vote
up vote
27
down vote
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))
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))
answered Sep 25 at 8:27
Aran-Fey
20.4k53165
20.4k53165
Why use itertools when you can use list expression?
â Moonsik Park
Sep 25 at 8:28
5
@MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
â Aran-Fey
Sep 25 at 8:29
add a comment |Â
Why use itertools when you can use list expression?
â Moonsik Park
Sep 25 at 8:28
5
@MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
â Aran-Fey
Sep 25 at 8:29
Why use itertools when you can use list expression?
â Moonsik Park
Sep 25 at 8:28
Why use itertools when you can use list expression?
â Moonsik Park
Sep 25 at 8:28
5
5
@MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
â Aran-Fey
Sep 25 at 8:29
@MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
â Aran-Fey
Sep 25 at 8:29
add a comment |Â
up vote
7
down vote
Yet another possibility, this time with enumerate
:
[x * (i % (n + m) < n) for i, x in enumerate(my_list)]
It uses the fact that False
and True
are equal to 0
and 1
in Python (see here).
As a bonus, it works fine even if the list isn't constant:
>>> n = 4
>>> m = 2
>>> my_list = range(20)
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
[0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]
If the list contains strings, it replaces them with an empty string instead of 0
:
>>> my_list = 'abcdefghijk'
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']
add a comment |Â
up vote
7
down vote
Yet another possibility, this time with enumerate
:
[x * (i % (n + m) < n) for i, x in enumerate(my_list)]
It uses the fact that False
and True
are equal to 0
and 1
in Python (see here).
As a bonus, it works fine even if the list isn't constant:
>>> n = 4
>>> m = 2
>>> my_list = range(20)
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
[0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]
If the list contains strings, it replaces them with an empty string instead of 0
:
>>> my_list = 'abcdefghijk'
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']
add a comment |Â
up vote
7
down vote
up vote
7
down vote
Yet another possibility, this time with enumerate
:
[x * (i % (n + m) < n) for i, x in enumerate(my_list)]
It uses the fact that False
and True
are equal to 0
and 1
in Python (see here).
As a bonus, it works fine even if the list isn't constant:
>>> n = 4
>>> m = 2
>>> my_list = range(20)
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
[0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]
If the list contains strings, it replaces them with an empty string instead of 0
:
>>> my_list = 'abcdefghijk'
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']
Yet another possibility, this time with enumerate
:
[x * (i % (n + m) < n) for i, x in enumerate(my_list)]
It uses the fact that False
and True
are equal to 0
and 1
in Python (see here).
As a bonus, it works fine even if the list isn't constant:
>>> n = 4
>>> m = 2
>>> my_list = range(20)
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
[0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]
If the list contains strings, it replaces them with an empty string instead of 0
:
>>> my_list = 'abcdefghijk'
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']
answered Sep 25 at 11:51
Eric Duminil
38.5k53064
38.5k53064
add a comment |Â
add a comment |Â
up vote
6
down vote
This worked for me:
list = [10] * 95
n = 4
m = 2
amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]
list = np.asarray(list)*amask
which outputs:
array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0.])
The code takes n
and m
and constructs a mask of ones and zeros with a length matching your initial list
using the np.tile
function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n
and m
.
You can cast the array back to a list if you want.
1
numpy
? For real?
â Alfe
Sep 25 at 8:19
1
@Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
â Eric Duminil
Sep 25 at 9:51
@EricDuminil Just overkill for the job, that's all. It's like asking for aprint()
and getting af=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close()
. Works, yeah. But adds unnecessary complexity.
â Alfe
Sep 25 at 10:41
1
Btw, innumpy
, I would have done it as(np.arange(95) % 5 < 3) * 10
.
â Alfe
Sep 25 at 10:44
3
@Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
â Shintlor
Sep 25 at 12:19
 |Â
show 1 more comment
up vote
6
down vote
This worked for me:
list = [10] * 95
n = 4
m = 2
amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]
list = np.asarray(list)*amask
which outputs:
array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0.])
The code takes n
and m
and constructs a mask of ones and zeros with a length matching your initial list
using the np.tile
function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n
and m
.
You can cast the array back to a list if you want.
1
numpy
? For real?
â Alfe
Sep 25 at 8:19
1
@Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
â Eric Duminil
Sep 25 at 9:51
@EricDuminil Just overkill for the job, that's all. It's like asking for aprint()
and getting af=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close()
. Works, yeah. But adds unnecessary complexity.
â Alfe
Sep 25 at 10:41
1
Btw, innumpy
, I would have done it as(np.arange(95) % 5 < 3) * 10
.
â Alfe
Sep 25 at 10:44
3
@Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
â Shintlor
Sep 25 at 12:19
 |Â
show 1 more comment
up vote
6
down vote
up vote
6
down vote
This worked for me:
list = [10] * 95
n = 4
m = 2
amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]
list = np.asarray(list)*amask
which outputs:
array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0.])
The code takes n
and m
and constructs a mask of ones and zeros with a length matching your initial list
using the np.tile
function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n
and m
.
You can cast the array back to a list if you want.
This worked for me:
list = [10] * 95
n = 4
m = 2
amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]
list = np.asarray(list)*amask
which outputs:
array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
10., 10., 10., 0.])
The code takes n
and m
and constructs a mask of ones and zeros with a length matching your initial list
using the np.tile
function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n
and m
.
You can cast the array back to a list if you want.
edited Sep 25 at 8:21
answered Sep 25 at 8:17
Shintlor
35919
35919
1
numpy
? For real?
â Alfe
Sep 25 at 8:19
1
@Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
â Eric Duminil
Sep 25 at 9:51
@EricDuminil Just overkill for the job, that's all. It's like asking for aprint()
and getting af=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close()
. Works, yeah. But adds unnecessary complexity.
â Alfe
Sep 25 at 10:41
1
Btw, innumpy
, I would have done it as(np.arange(95) % 5 < 3) * 10
.
â Alfe
Sep 25 at 10:44
3
@Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
â Shintlor
Sep 25 at 12:19
 |Â
show 1 more comment
1
numpy
? For real?
â Alfe
Sep 25 at 8:19
1
@Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
â Eric Duminil
Sep 25 at 9:51
@EricDuminil Just overkill for the job, that's all. It's like asking for aprint()
and getting af=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close()
. Works, yeah. But adds unnecessary complexity.
â Alfe
Sep 25 at 10:41
1
Btw, innumpy
, I would have done it as(np.arange(95) % 5 < 3) * 10
.
â Alfe
Sep 25 at 10:44
3
@Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
â Shintlor
Sep 25 at 12:19
1
1
numpy
? For real?â Alfe
Sep 25 at 8:19
numpy
? For real?â Alfe
Sep 25 at 8:19
1
1
@Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
â Eric Duminil
Sep 25 at 9:51
@Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
â Eric Duminil
Sep 25 at 9:51
@EricDuminil Just overkill for the job, that's all. It's like asking for a
print()
and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close()
. Works, yeah. But adds unnecessary complexity.â Alfe
Sep 25 at 10:41
@EricDuminil Just overkill for the job, that's all. It's like asking for a
print()
and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close()
. Works, yeah. But adds unnecessary complexity.â Alfe
Sep 25 at 10:41
1
1
Btw, in
numpy
, I would have done it as (np.arange(95) % 5 < 3) * 10
.â Alfe
Sep 25 at 10:44
Btw, in
numpy
, I would have done it as (np.arange(95) % 5 < 3) * 10
.â Alfe
Sep 25 at 10:44
3
3
@Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
â Shintlor
Sep 25 at 12:19
@Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
â Shintlor
Sep 25 at 12:19
 |Â
show 1 more comment
up vote
4
down vote
How about this?
my_list = [10] * 95
n = 3
m = 2
for i in range(n, len(my_list)-1, n+m):
my_list[i:i+m] = [0]*m
print(my_list)
Edit
I found out that the above code changes the length of resulting list in some cases.
>>> a = [1,2,3]
>>> a[2:4] = [0] * 2
>>> a
[1, 2, 0, 0]
Thus, the length should be restored somehow.
my_list = [10] * 95
cp_list = list(my_list)
n = 3
m = 5
for i in range(n, len(my_list)-1, n+m):
cp_list[i:i+m] = [0]*m
cp_list = cp_list[:len(my_list)]
print(cp_list)
1
Nice approach. But only iflen(my_list)
is smaller thanm
, this is more efficient than my solution.
â Alfe
Sep 25 at 8:24
1
There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
â Alfe
Sep 25 at 8:29
2
For deleting the last elements of a list, best usedel cp_list[n:]
.
â Alfe
Sep 25 at 14:58
add a comment |Â
up vote
4
down vote
How about this?
my_list = [10] * 95
n = 3
m = 2
for i in range(n, len(my_list)-1, n+m):
my_list[i:i+m] = [0]*m
print(my_list)
Edit
I found out that the above code changes the length of resulting list in some cases.
>>> a = [1,2,3]
>>> a[2:4] = [0] * 2
>>> a
[1, 2, 0, 0]
Thus, the length should be restored somehow.
my_list = [10] * 95
cp_list = list(my_list)
n = 3
m = 5
for i in range(n, len(my_list)-1, n+m):
cp_list[i:i+m] = [0]*m
cp_list = cp_list[:len(my_list)]
print(cp_list)
1
Nice approach. But only iflen(my_list)
is smaller thanm
, this is more efficient than my solution.
â Alfe
Sep 25 at 8:24
1
There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
â Alfe
Sep 25 at 8:29
2
For deleting the last elements of a list, best usedel cp_list[n:]
.
â Alfe
Sep 25 at 14:58
add a comment |Â
up vote
4
down vote
up vote
4
down vote
How about this?
my_list = [10] * 95
n = 3
m = 2
for i in range(n, len(my_list)-1, n+m):
my_list[i:i+m] = [0]*m
print(my_list)
Edit
I found out that the above code changes the length of resulting list in some cases.
>>> a = [1,2,3]
>>> a[2:4] = [0] * 2
>>> a
[1, 2, 0, 0]
Thus, the length should be restored somehow.
my_list = [10] * 95
cp_list = list(my_list)
n = 3
m = 5
for i in range(n, len(my_list)-1, n+m):
cp_list[i:i+m] = [0]*m
cp_list = cp_list[:len(my_list)]
print(cp_list)
How about this?
my_list = [10] * 95
n = 3
m = 2
for i in range(n, len(my_list)-1, n+m):
my_list[i:i+m] = [0]*m
print(my_list)
Edit
I found out that the above code changes the length of resulting list in some cases.
>>> a = [1,2,3]
>>> a[2:4] = [0] * 2
>>> a
[1, 2, 0, 0]
Thus, the length should be restored somehow.
my_list = [10] * 95
cp_list = list(my_list)
n = 3
m = 5
for i in range(n, len(my_list)-1, n+m):
cp_list[i:i+m] = [0]*m
cp_list = cp_list[:len(my_list)]
print(cp_list)
edited Sep 25 at 8:33
answered Sep 25 at 8:18
klim
51239
51239
1
Nice approach. But only iflen(my_list)
is smaller thanm
, this is more efficient than my solution.
â Alfe
Sep 25 at 8:24
1
There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
â Alfe
Sep 25 at 8:29
2
For deleting the last elements of a list, best usedel cp_list[n:]
.
â Alfe
Sep 25 at 14:58
add a comment |Â
1
Nice approach. But only iflen(my_list)
is smaller thanm
, this is more efficient than my solution.
â Alfe
Sep 25 at 8:24
1
There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
â Alfe
Sep 25 at 8:29
2
For deleting the last elements of a list, best usedel cp_list[n:]
.
â Alfe
Sep 25 at 14:58
1
1
Nice approach. But only if
len(my_list)
is smaller than m
, this is more efficient than my solution.â Alfe
Sep 25 at 8:24
Nice approach. But only if
len(my_list)
is smaller than m
, this is more efficient than my solution.â Alfe
Sep 25 at 8:24
1
1
There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
â Alfe
Sep 25 at 8:29
There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
â Alfe
Sep 25 at 8:29
2
2
For deleting the last elements of a list, best use
del cp_list[n:]
.â Alfe
Sep 25 at 14:58
For deleting the last elements of a list, best use
del cp_list[n:]
.â Alfe
Sep 25 at 14:58
add a comment |Â
up vote
3
down vote
numpy
can do this pretty concisely, too!
a = np.array(my_list).reshape(-1, n + m)
a[:, n:] = 0
result = a.ravel().tolist()
2
It doesn't seem to work withn = 4
andm = 2
. It raisesValueError: cannot reshape array of size 95 into shape (6)
.
â Eric Duminil
Sep 25 at 9:57
@EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
â timgeb
Sep 25 at 10:02
Please take a look at the second half of the question. This use case is specifically mentioned by OP.
â Eric Duminil
Sep 25 at 10:03
3
@EricDuminil you are right. This answer does not work in the latter case.
â timgeb
Sep 25 at 10:05
add a comment |Â
up vote
3
down vote
numpy
can do this pretty concisely, too!
a = np.array(my_list).reshape(-1, n + m)
a[:, n:] = 0
result = a.ravel().tolist()
2
It doesn't seem to work withn = 4
andm = 2
. It raisesValueError: cannot reshape array of size 95 into shape (6)
.
â Eric Duminil
Sep 25 at 9:57
@EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
â timgeb
Sep 25 at 10:02
Please take a look at the second half of the question. This use case is specifically mentioned by OP.
â Eric Duminil
Sep 25 at 10:03
3
@EricDuminil you are right. This answer does not work in the latter case.
â timgeb
Sep 25 at 10:05
add a comment |Â
up vote
3
down vote
up vote
3
down vote
numpy
can do this pretty concisely, too!
a = np.array(my_list).reshape(-1, n + m)
a[:, n:] = 0
result = a.ravel().tolist()
numpy
can do this pretty concisely, too!
a = np.array(my_list).reshape(-1, n + m)
a[:, n:] = 0
result = a.ravel().tolist()
answered Sep 25 at 8:42
timgeb
37.5k104875
37.5k104875
2
It doesn't seem to work withn = 4
andm = 2
. It raisesValueError: cannot reshape array of size 95 into shape (6)
.
â Eric Duminil
Sep 25 at 9:57
@EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
â timgeb
Sep 25 at 10:02
Please take a look at the second half of the question. This use case is specifically mentioned by OP.
â Eric Duminil
Sep 25 at 10:03
3
@EricDuminil you are right. This answer does not work in the latter case.
â timgeb
Sep 25 at 10:05
add a comment |Â
2
It doesn't seem to work withn = 4
andm = 2
. It raisesValueError: cannot reshape array of size 95 into shape (6)
.
â Eric Duminil
Sep 25 at 9:57
@EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
â timgeb
Sep 25 at 10:02
Please take a look at the second half of the question. This use case is specifically mentioned by OP.
â Eric Duminil
Sep 25 at 10:03
3
@EricDuminil you are right. This answer does not work in the latter case.
â timgeb
Sep 25 at 10:05
2
2
It doesn't seem to work with
n = 4
and m = 2
. It raises ValueError: cannot reshape array of size 95 into shape (6)
.â Eric Duminil
Sep 25 at 9:57
It doesn't seem to work with
n = 4
and m = 2
. It raises ValueError: cannot reshape array of size 95 into shape (6)
.â Eric Duminil
Sep 25 at 9:57
@EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
â timgeb
Sep 25 at 10:02
@EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
â timgeb
Sep 25 at 10:02
Please take a look at the second half of the question. This use case is specifically mentioned by OP.
â Eric Duminil
Sep 25 at 10:03
Please take a look at the second half of the question. This use case is specifically mentioned by OP.
â Eric Duminil
Sep 25 at 10:03
3
3
@EricDuminil you are right. This answer does not work in the latter case.
â timgeb
Sep 25 at 10:05
@EricDuminil you are right. This answer does not work in the latter case.
â timgeb
Sep 25 at 10:05
add a comment |Â
up vote
3
down vote
[j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
Maybe?
Result
>>> num, input_num, m, n=95, 10, 2, 3
>>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
[10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]
3
I guess the list full of10
is just for an example...
â Julien
Sep 25 at 8:07
@Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
â Moonsik Park
Sep 25 at 8:20
1
1) Your output is incorrect (it's[10, 10, 0, 0, 0]
instead of[10, 10, 10, 0, 0]
) 2) Concatenating lists withsum
is an antipattern with a massive run time complexity.
â Aran-Fey
Sep 25 at 8:34
@Aran-Fey Nope, it's correct.
â Moonsik Park
Sep 25 at 8:39
Oops. Indeed it is. Edited.
â Moonsik Park
Sep 25 at 8:44
add a comment |Â
up vote
3
down vote
[j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
Maybe?
Result
>>> num, input_num, m, n=95, 10, 2, 3
>>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
[10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]
3
I guess the list full of10
is just for an example...
â Julien
Sep 25 at 8:07
@Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
â Moonsik Park
Sep 25 at 8:20
1
1) Your output is incorrect (it's[10, 10, 0, 0, 0]
instead of[10, 10, 10, 0, 0]
) 2) Concatenating lists withsum
is an antipattern with a massive run time complexity.
â Aran-Fey
Sep 25 at 8:34
@Aran-Fey Nope, it's correct.
â Moonsik Park
Sep 25 at 8:39
Oops. Indeed it is. Edited.
â Moonsik Park
Sep 25 at 8:44
add a comment |Â
up vote
3
down vote
up vote
3
down vote
[j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
Maybe?
Result
>>> num, input_num, m, n=95, 10, 2, 3
>>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
[10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]
[j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
Maybe?
Result
>>> num, input_num, m, n=95, 10, 2, 3
>>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
[10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]
edited Sep 25 at 8:45
Aran-Fey
20.4k53165
20.4k53165
answered Sep 25 at 8:06
Moonsik Park
4594
4594
3
I guess the list full of10
is just for an example...
â Julien
Sep 25 at 8:07
@Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
â Moonsik Park
Sep 25 at 8:20
1
1) Your output is incorrect (it's[10, 10, 0, 0, 0]
instead of[10, 10, 10, 0, 0]
) 2) Concatenating lists withsum
is an antipattern with a massive run time complexity.
â Aran-Fey
Sep 25 at 8:34
@Aran-Fey Nope, it's correct.
â Moonsik Park
Sep 25 at 8:39
Oops. Indeed it is. Edited.
â Moonsik Park
Sep 25 at 8:44
add a comment |Â
3
I guess the list full of10
is just for an example...
â Julien
Sep 25 at 8:07
@Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
â Moonsik Park
Sep 25 at 8:20
1
1) Your output is incorrect (it's[10, 10, 0, 0, 0]
instead of[10, 10, 10, 0, 0]
) 2) Concatenating lists withsum
is an antipattern with a massive run time complexity.
â Aran-Fey
Sep 25 at 8:34
@Aran-Fey Nope, it's correct.
â Moonsik Park
Sep 25 at 8:39
Oops. Indeed it is. Edited.
â Moonsik Park
Sep 25 at 8:44
3
3
I guess the list full of
10
is just for an example...â Julien
Sep 25 at 8:07
I guess the list full of
10
is just for an example...â Julien
Sep 25 at 8:07
@Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
â Moonsik Park
Sep 25 at 8:20
@Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
â Moonsik Park
Sep 25 at 8:20
1
1
1) Your output is incorrect (it's
[10, 10, 0, 0, 0]
instead of [10, 10, 10, 0, 0]
) 2) Concatenating lists with sum
is an antipattern with a massive run time complexity.â Aran-Fey
Sep 25 at 8:34
1) Your output is incorrect (it's
[10, 10, 0, 0, 0]
instead of [10, 10, 10, 0, 0]
) 2) Concatenating lists with sum
is an antipattern with a massive run time complexity.â Aran-Fey
Sep 25 at 8:34
@Aran-Fey Nope, it's correct.
â Moonsik Park
Sep 25 at 8:39
@Aran-Fey Nope, it's correct.
â Moonsik Park
Sep 25 at 8:39
Oops. Indeed it is. Edited.
â Moonsik Park
Sep 25 at 8:44
Oops. Indeed it is. Edited.
â Moonsik Park
Sep 25 at 8:44
add a comment |Â
up vote
0
down vote
Also in the itertools family, you can repeat
a desired pattern:
Given
import itertools as it
m, n = 2, 3
p = n + 1
Code
pattern = it.repeat([10] * n + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]
pattern = it.repeat([10] * p + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]
Test
assert len(res) == 95
However, @Aran-Fey's itertools.cycle
solution is cleaner as it does not require chaining.
add a comment |Â
up vote
0
down vote
Also in the itertools family, you can repeat
a desired pattern:
Given
import itertools as it
m, n = 2, 3
p = n + 1
Code
pattern = it.repeat([10] * n + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]
pattern = it.repeat([10] * p + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]
Test
assert len(res) == 95
However, @Aran-Fey's itertools.cycle
solution is cleaner as it does not require chaining.
add a comment |Â
up vote
0
down vote
up vote
0
down vote
Also in the itertools family, you can repeat
a desired pattern:
Given
import itertools as it
m, n = 2, 3
p = n + 1
Code
pattern = it.repeat([10] * n + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]
pattern = it.repeat([10] * p + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]
Test
assert len(res) == 95
However, @Aran-Fey's itertools.cycle
solution is cleaner as it does not require chaining.
Also in the itertools family, you can repeat
a desired pattern:
Given
import itertools as it
m, n = 2, 3
p = n + 1
Code
pattern = it.repeat([10] * n + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]
pattern = it.repeat([10] * p + [0] * m)
res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
print(res)
# [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]
Test
assert len(res) == 95
However, @Aran-Fey's itertools.cycle
solution is cleaner as it does not require chaining.
answered 2 days ago
pylang
12k23349
12k23349
add a comment |Â
add a comment |Â
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52493328%2fperiodically-replacing-values-in-a-list%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like
[10, 10, 10, 0, 0, ...]
or do you want to overwrite every nth value in an existing list?â Aran-Fey
Sep 25 at 8:13
6
How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
â Denny
Sep 25 at 11:15
1
@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
â Riley
Sep 25 at 11:22
3
Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
â user202729
Sep 25 at 13:08
3
It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
â user202729
Sep 25 at 15:17