如何弹出堆栈,直到使用for loop的空为空?
S=['TOM', 'HARRY', 'MAMA', 'JOE']
print(S)
for x in S:
print(S.pop())
if S==[]:
print("Empty")
break
使用for循环应该在整个列表中迭代,并给我所有的项目,然后给我“空”,但它仅给出了
我所得到的
['TOM', 'HARRY', 'MAMA', 'JOE']
JOE
MAMA
两个元素- 我期望的
['TOM', 'HARRY', 'MAMA', 'JOE']
JOE
MAMA
HARRY
TOM
Empty
是我的第一个问题,所以上面有任何提示如何构架问题将不胜感激。
S=['TOM', 'HARRY', 'MAMA', 'JOE']
print(S)
for x in S:
print(S.pop())
if S==[]:
print("Empty")
break
Using a for loop should iterate through the entire list and give me all the items followed by 'Empty' but instead, it only gives two elements
What I'm getting-
['TOM', 'HARRY', 'MAMA', 'JOE']
JOE
MAMA
What I was expecting-
['TOM', 'HARRY', 'MAMA', 'JOE']
JOE
MAMA
HARRY
TOM
Empty
This is my first question here so any tips on how to frame questions would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
代码的主要问题是,在对该列表进行更改时,您不能循环浏览列表。如果要使用循环的
(Timgeb建议很棒)。您可以做到这一点:
这将照顾列表的所有项目
The main issue with your code is that you can't loop over a list while doing changes to that list. If you want to use a
for
loop (timgeb suggestion is great btw). You could do this:This will take care of popping all the items of the list
您会看到意外的结果,因为您在迭代时会突变列表。请注意,您没有使用
X
做任何事情,因此循环的在这里不是正确的工具。
循环使用
。
You see an unexpected result because you're mutating the list while iterating over it. Note that you're not doing anything with
x
, so afor
loop is not the right tool here.Use a
while
loop.