python - 如何遍历枚举对象并使用 next() 函数打印所有索引项对?

标签 python

我有以下程序

enum1 = enumerate("This is the test string".split())

我需要遍历 enum1 并使用 next() 函数打印所有索引项对。

我尝试通过执行以下操作来获取索引项对

for i in range(len(enum1)):
    print enum1.next()

它抛出一个错误,显示 len() 不能应用于枚举。

谁能建议我使用 next() 函数遍历此枚举以打印所有索引项对的方法?

注意:我的要求是使用next() 函数来检索索引项对

最佳答案

只需使用:

for i,item in enum1:
   # i is the index
   # item is your item in enum1

for i,item in enumerate("This is the test string".split()):
   # i is the index
   # item is your item in enum1

这将使用下面的 next 方法...

关于python - 如何遍历枚举对象并使用 next() 函数打印所有索引项对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6411127/

相关文章:

python - 为什么不鼓励混合使用 'from x import y' 和 'import x'?

python - 抓取滚动时加载内容的动态网站

python - 从 GCP 安装文档运行 "[CRITICAL] WORKER TIMEOUT"时,日志中的 "Hello Cloud Run with Python"

python - 单元测试 : same test class with mutliple datasets

python - 应用于可迭代对象的每个元素的 bool 语句分支

python - 与 pandas 中的 dropna() 相反

python - 提取数组中的每 3 个数据

python - 为什么我不能在 python 中使用 print in if 三元运算符?

python - 如何将数字添加到 pandas 数组的索引范围

尝试使用用户定义的类时出现 Python NameError