我正在编写一个小的代码片段,使用list appends和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'?在
谢谢
你一蹦就把名单缩短了。在
简单地把绳子倒过来怎么样。在
在你的代码中:
^{pr2}$见下文。因为您正在使用迭代器(for。。英寸)。 您可以直接看到迭代器的详细信息,以及改变列表会给迭代器带来怎样的麻烦。在
本质上与:
^{pr2}$第一次迭代i是0,len(strList)是4,您可以pop+append“d”。在
第二次迭代i是1,len(strList)是3,然后pop+append“c”。在
第三次迭代i是2,len(strList)是2,所以循环条件失败,就完成了。在
(这实际上是通过列表上的迭代器完成的,而不是局部变量'i'。为了清楚起见,我这样展示。)
如果你想操作你正在迭代的序列,通常最好使用while循环。例如:
相关问题 更多 >
编程相关推荐