[英]Reversing list element in python
How to reverse list element one by one in python?如何在python中一一反转列表元素? I tried nested loop.
我试过嵌套循环。 But I couldn`t display second loop as "Result"
但我无法将第二个循环显示为“结果”
For example:例如:
Input: 102 346 5897
输入:
102 346 5897
Result: 201 643 7985
结果:
201 643 7985
Assuming your input list consists of strings, you go like this:假设您的输入列表由字符串组成,您可以像这样:
> a = ['102','346','5897']
> for i in a:
> print(i[::-1],end=' ')
returns 201 643 7985
返回
201 643 7985
You can use [::-1]
您可以使用
[::-1]
string='102 346 5897'
lst=string.split()[::-1]
print(' '.join(lst))
Try the following solution.尝试以下解决方案。 you can use [::-1] to reverse a string.
您可以使用 [::-1] 来反转字符串。
x = ["123", "456", "789"]
y = []
for i in range(0,len(x)):
y.append(x[i][::-1])
print(y)
['321', '654', '987']
You can use following trick with number inputs assuming inputs are numbers.假设输入是数字,您可以对数字输入使用以下技巧。
x = [123, 456, 789]
y = []
for i in range(0,len(x)):
y.append(int(str(x[i])[::-1]))
print(y)
[321, 654, 987]
code
代码
def Reverse(lst):
lst.reverse()
return lst
lst = ["123", "456", "789"]
print(Reverse(lst))
output
输出
['789', '456', '123']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.