How to do this?

Peter Otten __peter__ at web.de
Mon Apr 1 07:32:29 EDT 2013


Ana Dionísio wrote:

> Nice! Thank you!
> 
> And if I need something like this?
> 
> [0 0 0 0 0.17 0.17 0.17 0.17 0 0 0 0.17 0.17 0.17 0 0 0 0 0 0 0]
> 
> How can I do this?

With vanilla Python:

>>> vt = [0] * 20
>>> for i, v in enumerate(vt):
...     if 4 <= i < 8 or 13 <= i < 16:
...             vt[i] = .17
... 
>>> vt
[0, 0, 0, 0, 0.17, 0.17, 0.17, 0.17, 0, 0, 0, 0, 0, 0.17, 0.17, 0.17, 0, 0, 
0, 0]

With vanilla Python using slices:

>>> vt = [0] * 20
>>> vt[4:8] = [.17]*4
>>> vt[13:16] = [.17]*3
>>> vt
[0, 0, 0, 0, 0.17, 0.17, 0.17, 0.17, 0, 0, 0, 0, 0, 0.17, 0.17, 0.17, 0, 0, 
0, 0]

With numpy:

>>> vt = numpy.zeros(20)
>>> vt[4:8] = vt[13:16] = .17
>>> vt
array([ 0.  ,  0.  ,  0.  ,  0.  ,  0.17,  0.17,  0.17,  0.17,  0.  ,
        0.  ,  0.  ,  0.  ,  0.  ,  0.17,  0.17,  0.17,  0.  ,  0.  ,
        0.  ,  0.  ])





More information about the Python-list mailing list