quantumdisaster
quantumdisaster

Reputation: 587

python backwards lists

say I have a list of numbers [122,423,134] and I wanted to reverse the individual elements so they are [221,324,431], How would I do this in python? reversed(list) and list.reverse() only reverse the order of the elements. Probably something trivial I am sure. Thanks for the help.

Upvotes: 1

Views: 490

Answers (3)

Anders Waldenborg
Anders Waldenborg

Reputation: 3035

You can use either map or a list compahension to transform each element of a list. Given a function named xform you can do:

newlist = map(xform, oldlist)

Or:

newlist = [xform(a) for a in oldlist]

Now you just need to write the xform function.

def decimalreverse(i):
    l = reversed(str(i))
    return int(''.join(l))

Upvotes: 0

Rusty Rob
Rusty Rob

Reputation: 17173

>>> _list=[122,423,134]
>>> _list=[int("".join(reversed(str(i)))) for i in _list]
>>> _list
[221, 324, 431]

another solution:

>>> def reverse_number(i):
...     i=str(i)
...     i=i[::-1]
...     i=int(i)
...     return i
... 
>>> _list=[122,423,134]
>>> map(reverse_number,_list)
[221, 324, 431]
or
>>>> [reverse_number(i) for i in _list]

Upvotes: 2

NPE
NPE

Reputation: 500177

In [1]: l = [122,423,134]

In [2]: [int(str(val)[::-1]) for val in l]
Out[2]: [221, 324, 431]

Here, str(val) converts the element to a string, [::-1] reverses the string, and int() converts the result to an integer.

Upvotes: 12

Related Questions