如何弹出堆栈,直到使用for loop的空为空?

发布于 2025-02-03 14:14:05 字数 415 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

同展鸳鸯锦 2025-02-10 14:14:05

代码的主要问题是,在对该列表进行更改时,您不能循环浏览列表。如果要使用循环的(Timgeb建议很棒)。您可以做到这一点:

for _ in range(len(S)):
    print(S.pop())

这将照顾列表的所有项目

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:

for _ in range(len(S)):
    print(S.pop())

This will take care of popping all the items of the list

┈┾☆殇 2025-02-10 14:14:05

您会看到意外的结果,因为您在迭代时会突变列表。请注意,您没有使用X做任何事情,因此循环的在这里不是正确的工具。

循环使用

while S:
    print(S.pop())

print('empty')

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 a for loop is not the right tool here.

Use a while loop.

while S:
    print(S.pop())

print('empty')
木格 2025-02-10 14:14:05
S=['TOM', 'HARRY', 'MAMA', 'JOE']
print(S)
for x in S[::-1]:
    print(S.pop())
    if S==[]:
        print("Empty")
        break
S=['TOM', 'HARRY', 'MAMA', 'JOE']
print(S)
for x in S[::-1]:
    print(S.pop())
    if S==[]:
        print("Empty")
        break
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文