使用反向列表问题列表.pop()

2024-10-01 09:20:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小的代码片段,使用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'?在

谢谢


Tags: 字符串代码inforinputrawpoplist
3条回答

你一蹦就把名单缩短了。在

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

简单地把绳子倒过来怎么样。在

>>> x = 'abcd'
>>> x[::-1]
'dcba'
>>> 

在你的代码中:

Never mutate the list on which you are iterating with. It can cause subtle errors.

^{pr2}$

见下文。因为您正在使用迭代器(for。。英寸)。 您可以直接看到迭代器的详细信息,以及改变列表会给迭代器带来怎样的麻烦。在

>>> strList = [1, 2, 3, 4, 5]
>>> k = strList.__iter__()
>>> k.next()
1
>>> k.__length_hint__()   <--- Still 4 to go
4
>>> strList.pop()         <---- You pop an element
5
>>> k.__length_hint__()   <----- Now only 3 to go
3
>>> 
>>> k.next()
2
>>> k.__length_hint__()
2
for someChar in strList:
    reverseCharList.append(strList.pop())

本质上与:

^{pr2}$

第一次迭代i是0,len(strList)是4,您可以pop+append“d”。在

第二次迭代i是1,len(strList)是3,然后pop+append“c”。在

第三次迭代i是2,len(strList)是2,所以循环条件失败,就完成了。在

(这实际上是通过列表上的迭代器完成的,而不是局部变量'i'。为了清楚起见,我这样展示。)

如果你想操作你正在迭代的序列,通常最好使用while循环。例如:

while strList:
    reverseCharList.append(strList.pop())

相关问题 更多 >