Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用list.pop()反转列表时出现问题_Python_Loops_Stack_Reverse - Fatal编程技术网

Python 使用list.pop()反转列表时出现问题

Python 使用list.pop()反转列表时出现问题,python,loops,stack,reverse,Python,Loops,Stack,Reverse,我当时正在编写一个小代码段,使用列表附件和pop反转字符串 我写的剧本如下: someStr = raw_input("Enter some string here:") strList = [] for c in someStr: strList.append(c) print strList reverseCharList = [] for someChar in strList: reverseCharList.append(strList.pop()) print

我当时正在编写一个小代码段,使用列表附件和pop反转字符串

我写的剧本如下:

someStr = raw_input("Enter some string here:")
strList = []
for c in someStr:
    strList.append(c)

print strList

reverseCharList = []
for someChar in strList:
    reverseCharList.append(strList.pop())

print reverseCharList
输入字符串abcd时,返回的输出为[d,c]


我知道我正在修改我正在迭代的列表,但是有人能解释为什么这里不显示字符“a”和“b”吗


谢谢

简单的字符串反转怎么样

>>> x = 'abcd'
>>> x[::-1]
'dcba'
>>> 
在您的代码上:

永远不要改变正在迭代的列表。它会导致细微的错误

strList=[1,2,3,4,5] >>>反向列表=[] >>>对于strList中的someChar: ... 打印strList ... reverseCharList.append(strList.pop()) ... 打印strList ... [1,2,3,4,5]strList=[1,2,3,4,5] >>>k=strList.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu() >>>k.下一步() 1. >>>k.\uuuu length\u hint\uuuuu()>>strList.pop()>>k.\uuu length\u hint\uuuuuu()>> >>>k.下一步() 2. >>>k.uuu长度u提示uuuu() 2. 基本上与以下内容相同:

i = 0
while i < len(strList):
    reverseCharList.append(strList.pop())
    i += 1

当你弹出时,你会缩短列表

reverseCharList = []
while strList:
    reverseCharList.append(strList.pop())

一个简单的接收版本:

def reverse(the_list):
    if not the_list:
        return []
    return [the_list.pop()] + reverse(the_list)

当然,
[].reverse()
更快。

这是学习递归的一个很好的练习!只是想确定一下:你确实知道
[].reverse()
,对吗?@Nathon-是的,我知道。我只是想知道输出中出现差异的原因。“我知道我正在修改我正在迭代的列表,但是……”你听说过一个故事吗,他去看医生说“医生,我这样做很痛”,医生回答说“那么,不要这样做!”:)说真的,不过我很高兴你的问题得到了回答。这个练习的目的是想弄清楚“为什么”当“那样”做的时候会痛。苏的好医生解释了“为什么”。谢谢你的替代版本。我只是想知道我发布的代码段出了什么问题。“”。join(reversed('abcd')也会做同样的事情,但根据timeit的说法,使用列表切片操作符进行操作的速度大约快9倍!完美的谢谢你的解释这是一个很好的解释。关于如何使用迭代器在Python中实现for-in构造函数,有什么地方可以让我看一下吗?@sc\u-ray:我提供了一个简单的例子,说明迭代器对改变序列的影响。
i = 0
while i < len(strList):
    reverseCharList.append(strList.pop())
    i += 1
while strList:
    reverseCharList.append(strList.pop())
reverseCharList = []
while strList:
    reverseCharList.append(strList.pop())
def reverse(the_list):
    if not the_list:
        return []
    return [the_list.pop()] + reverse(the_list)