跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Python] for 循环里面的迭代器到底怎么迭代的

发表于

为什么会产生这个问题?

因为我写了一个有问题的代码,大概长下面这样

# 如下是一个简单的循环
l = ['abc' ,2 ,[1, 2, 3]  ,4]
for i in l:
    print(i)
    l.remove(i)
print(l)

最后的输出是

abc
[1, 2, 3]
[2, 4]

踩坑的原因是,在遍历的时候,我根据一些条件去删除列表中的元素,然后偶然发现输出与我的预期并不符合。

原本的理解是next会依次返回后面一个元素,因此现在这个元素我删了也没事。

但是事实显然不是这样,列表产生的迭代器返回值好像是根据索引返回的

大模型的回答不同模型直接存在差异,因此在翻了一些 blog ,有一篇里面有句话如下所示

==迭代器本身并不存储任何数据项,存储的只是一个指针,该指针指向可迭代对象中真正存储的数据项,它指向当前被遍历到的数据项索引位置,下一次遍历则向后推进这个位置==

所以再次来求助一下,迭代器的 next 是按照索引来获取数据的吗

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.