1

Let's say I have a matrix [[-2,4],[-6,8]].

I want to know how to get the opposite of those numbers: [[2,-4],[6,-8]].

Is there a special function in Python I'm supposed to use?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
user2581724
  • 237
  • 3
  • 9
  • 20

4 Answers4

3

numpy is awesome :P

a = numpy.array( [[-2,4],[-6,8]])
a *= -1
print a
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

Using a list comprehension is one way to go about it:

>>> data = [[-2,4],[-6,8]]
>>> [[-ele for ele in item] for item in data]
[[2, -4], [6, -8]]
anon582847382
  • 19,907
  • 5
  • 54
  • 57
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
0
import numpy

matrix = numpy.array([[-2,4],[-6,8]])
negatedMatrix = matrix * -1

print negatedMatrix

Giving the output:

[[ 2 -4]
 [ 6 -8]]
0

If you do not want to import packages and you also have a problem with list comprehensions but you like unnecessary complicated things you can use map() and lambda like this:

data = [[-2,4],[-6,8]]
reversed_data = map(lambda sublist: map(lambda x: -x, sublist), data)
# [[2, -4], [6, -8]]

EDIT: This example is working in python 2.7. In python 3+ map() returns an iterator so you need to do list(map()) to get this result. (credit goes to SethMMorton)

skamsie
  • 2,614
  • 5
  • 36
  • 48
  • Note that in python3 `map` returns a *map object*, so you'd have to do `list(map())` to get this result in that case. – SethMMorton Apr 04 '14 at 19:45