[英]How to reverse a list of strings without reversed() or [::-1] in Python
I made a post about this recently but didn't go into proper detail and I don't really know how commenting works on this website so I thought I'd create another thread with proper detail (if that's okay, sorry if it isn't) 我最近对此发表了一篇文章,但没有详细介绍,而且我真的不知道该网站上的评论是如何工作的,因此我认为我将创建另一个具有适当详细信息的主题(如果可以的话,抱歉,如果不是这样的话)。 t)
Simply put, I'm writing code that prompts for and reads a string from a user (eg: 12345). 简而言之,我正在编写提示和读取用户字符串的代码(例如:12345)。 This string could be infinitely long (eg: 123456789123456789, etc).
该字符串可以是无限长的(例如:123456789123456789,等等)。 After this string is entered, my code then takes each element from that string and puts it into a list (eg, 12345 is turned into ['1', '2', '3', '4', '5']).
输入此字符串后,我的代码然后从该字符串中获取每个元素并将其放入列表中(例如,将12345转换为['1','2','3','4','5']) 。
What I need help with is reversing this list of strings without using reversed() or [::-1], and for it to work with a list of strings that could be infinitely long (eg, ['1', '2', '3', '4', '5'] turns into ['5', '4', '3', '2', '1']). 我需要帮助的是在不使用reversed()或[::-1]的情况下反转此字符串列表,并使其与可能无限长的字符串列表一起工作(例如['1','2' ,'3','4','5']变成['5','4','3','2','1'])。
I know this is very basic, but I've spent quite a while trying to think of how to do this and for some reason my slow brain can't grasp a way how to. 我知道这是非常基本的,但是我花了很多时间试图思考如何做到这一点,并且由于某种原因,我的慢大脑无法掌握如何做到这一点。 The best way for me to learn is to see it being done, with an explanation as to how it works (or I could look at the code and figure out the 'how' part by myself).
对我来说,最好的学习方法是看它完成了,并解释它是如何工作的(或者我可以自己看一下代码并弄清楚“如何做”)。 I would be extremely appreciative for help on this, and thankyou in advance!
在此方面,我将非常感谢您的帮助,并先谢谢您!
How about this 这个怎么样
x = input('enter the values:')
x = list(x)
res = []
for i in range(len(x) -1, -1, -1):
res.append(x[i])
print(res)
In addition to using reversed()
or L[::-1]
, you could use list.reverse()
to reverse the elements of the list in-place : 除了使用
reversed()
或L[::-1]
你可以使用list.reverse()
逆转就地列表的内容:
>>> L = ['1', '2', '3', '4', '5']
>>> L.reverse()
>>> L
['5', '4', '3', '2', '1']
You can implement reversed()
yourself with a for
loop: 您可以使用
for
循环自己实现reversed()
:
>>> L = ['1', '2', '3', '4', '5']
>>> R = []
>>> for i in range(len(L)-1, -1, -1):
... R.append(L[i])
...
>>> R
['5', '4', '3', '2', '1']
lst1 = [1,2,3,4,5,6]
reversed_list = []
length = len(lst1)
for r in range(0, length ):
reversed_list.append( lst1[length - r - 1] )
print reversed_list
x="hey there"
l=len(x)
out=''
while l:
out=out+x[l-1]
l-=1
print out
This is what you are looking for. 这就是您要寻找的。 Start at end of sting on work backwards and append it to an out var
从向后刺痛开始,然后将其附加到out var
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.