Reputation: 19164
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.
Upvotes: 2
Views: 489
Reputation: 369054
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]
map(..)
with list(map(..))
if you use Python 3.xUsing 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]
Upvotes: 18