sci-guy
sci-guy

Reputation: 2584

How can I reverse multirow python list

How can I reverse the lists of a matrix in python.

EG I have:

example= [1,2,3],
         [4,5,6],
         [7,8,9]

I want to reverse each row to get the following:

example_reversed = [3,2,1],
                   [6,5,4],
                   [9,8,7]

thanks!

Upvotes: 0

Views: 80

Answers (4)

Rick
Rick

Reputation: 45251

This should do it:

[list(reversed(L)) for L in example]

EDIT: Ugh. Way too slow, apparently.

Upvotes: 0

Thomas Baruchel
Thomas Baruchel

Reputation: 7517

Your matrix currently seems to be stored in a tuple, isn't it?

Anyway, try something like:

list(list(reversed(i)) for i in example)

But you should consider using Numpy if you need to do many computations with matrices.

Upvotes: 1

Malik Brahimi
Malik Brahimi

Reputation: 16711

Map the reversed function to each item:

newList = map(list, map(reversed, example))

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

You can use a list comprehension and reverse indexing :

>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> [i[::-1] for i in a]
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]

Upvotes: 4

Related Questions