Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negation of list in python

Tags:

python

list

I have a list :

v=[0, -0.01, 0, 0, 0.01, 0.25, 1]

I wanted the list to be :

v=[0, 0.01, 0, 0, -0.01, -0.25, -1]

which is the best way to do that? -v wont work.

like image 953
sam Avatar asked Jan 21 '26 03:01

sam


1 Answers

Using list comprehension:

>>> v=[0, -0.01, 0, 0, 0.01, 0.25, 1]
>>> [-x for x in v]
[0, 0.01, 0, 0, -0.01, -0.25, -1]

Using map with operator.neg:

>>> import operator
>>> map(operator.neg, v)
[0, 0.01, 0, 0, -0.01, -0.25, -1]
  • Replace map(..) with list(map(..)) if you use Python 3.x

Using numpy:

>>> import numpy as np
>>> -np.array(v)
array([-0.  ,  0.01, -0.  , -0.  , -0.01, -0.25, -1.  ])
>>> (-np.array(v)).tolist()
[-0.0, 0.01, -0.0, -0.0, -0.01, -0.25, -1.0]
like image 142
falsetru Avatar answered Jan 23 '26 16:01

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!