使用 list.pop() 反转列表的问题 [英] Issue with reversing list using list.pop()
问题描述
我正在编写一个小代码片段来使用列表追加和弹出来反转字符串.
我写的脚本如下:
someStr = raw_input("请在此处输入一些字符串:")strList = []对于 someStr 中的 c:strList.append(c)打印字符串列表reverseCharList = []对于 strList 中的 someChar:reverseCharList.append(strList.pop())打印 reverseCharList
当我输入一个字符串 abcd 时,返回的输出是 [d,c].
我知道我正在改变我正在迭代的列表,但有人可以解释为什么这里没有显示字符 'a' 和 'b' 吗?
谢谢
简单的字符串反转怎么样.
<预><代码>>>>x = 'abcd'>>>x[::-1]'dcba'>>>在您的代码上:
<块引用>永远不要改变你正在迭代的列表.它可能会导致细微的错误.
<预><代码>>>>strList = [1, 2, 3, 4, 5]>>>reverseCharList = []>>>对于 strList 中的 someChar:... 打印 strList... reverseCharList.append(strList.pop())... 打印 strList...[1, 2, 3, 4, 5] <-- 迭代1[1, 2, 3, 4][1, 2, 3, 4] <-- 迭代2[1, 2, 3][1, 2, 3] <-- 迭代 3[1, 2]
请参阅以下内容.由于您使用的是迭代器(for .. in ..).您可以直接查看迭代器的详细信息以及列表的变异如何与迭代器混淆.
<预><代码>>>>strList = [1, 2, 3, 4, 5]>>>k = strList.__iter__()>>>k.next()1>>>k.__length_hint__() <--- 还有 4 个4>>>strList.pop() <---- 你弹出一个元素5>>>k.__length_hint__() <----- 现在只剩下 3 个了3>>>>>>k.next()2>>>k.__length_hint__()2I was working on writing a small code snippet to reverse a string using list appends and pop.
The script that I wrote is as follows:
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
When I enter a string abcd, the output that's returned is [d,c].
I know I am mutating the list I am iterating over but can somebody explain why the chars 'a' and 'b' is not displayed here?
Thanks
How about a simple reversal of string.
>>> x = 'abcd'
>>> x[::-1]
'dcba'
>>>
On your code:
Never mutate the list on which you are iterating with. It can cause subtle errors.
>>> strList = [1, 2, 3, 4, 5]
>>> reverseCharList = []
>>> for someChar in strList:
... print strList
... reverseCharList.append(strList.pop())
... print strList
...
[1, 2, 3, 4, 5] <-- Iteration 1
[1, 2, 3, 4]
[1, 2, 3, 4] <-- Iteration 2
[1, 2, 3]
[1, 2, 3] <-- Iteration 3
[1, 2]
See the following. Since you are using iterator (for .. in ..). You can see the iterator details directly and how mutating the list messes up with iterator.
>>> 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
这篇关于使用 list.pop() 反转列表的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!