Home > Software design >  Reverse digits of a list of numbers in python
Reverse digits of a list of numbers in python

Time:04-01

for i in range(len(primo)):
    reversed_num = 0
    while i > 0:
       digit = i % 10
       reversed_num = reversed_num * 10   digit
       i //= 10
       reversed.append (reversed_num)
    
for r in range(len(reversed)):
    print (r)

I'm writing a program to reverse a series of numbers from a list. For example:

Input: 1234,124,654

Output: 4321,421,456

The script works correctly with one number, but with a list it doesn't work properly.

CodePudding user response:

You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object.

CodePudding user response:

Nice try, but what about a function that reverses the numbers? You should be happy to know that reversed already exists in Python, and you can use it this way:

>>> list(reversed(str(0.1223142131)))
['1', '3', '1', '2', '4', '1', '3', '2', '2', '1', '.', '0']
>>> float(''.join(list(reversed(str(0.1223142131)))))
1312413221.0

so you can implement your own function:

def myReverser(n: float) -> float:
    return float(''.join(list(reversed(str(n)))))

and then use it over the whole list:

reversedList = [myReverser(i) for i in [1234, 124, 654]]

CodePudding user response:

code:

l = input().split(',')
l = list(map(lambda x: list(map(lambda d: int(d), x))[::-1], l))
print(l)

input:

123,456,789

output:

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

CodePudding user response:

Well, you are only printing the range of the length, so I don't know how this would print your numbers at all. Here is a brief method that does what you are after, I believe.

In [1]: [int(str(x)[::-1]) for x in [1234, 124, 654]]
Out[1]: [4321, 421, 456]

or:

def reverse_items(l: list[int]) -> list[int]:
    return [int(str(x)[::-1]) for x in l]


if __name__ == "__main__":
    print(reverse_items([4321, 421, 456]))

output:

[1234, 124, 654]

This creates a list of integer values generated from reversing the string values of given list items.

  • Related