【问题标题】:Iterate through the same list starting from different points in Python从 Python 中的不同点开始遍历同一个列表
【发布时间】:2022-01-08 10:54:58
【问题描述】:

我想从两个不同的起点遍历同一个列表。 我可以这样做:

for LayerIndex in range(len( layers ) - 1):
    thisLayer = layers[LayerIndex     ]
    nextLayer = layers[LayerIndex + 1 ]

但我确信它应该有一个更 Pythonic 的方式来做到这一点。

【问题讨论】:

  • 我不太清楚你想在这里做什么。一个迭代器依赖于另一个迭代器还是独立的?为什么同时需要两个?

标签: python iterator iteration iterable


【解决方案1】:

作为一个选项,您可以从该列表的枚举中提取该列表的索引:

for index, elem in enumerate(layers):        
    if(index<(len(layers)-1)):    
        thiseLayer= elem        
        nexteLayer= layers[index+1]

这里额外的if 只是检查下一个元素是否确实存在。

我不确定这是否更“Pythonic”

【讨论】:

    【解决方案2】:

    是的,你可以这样做,但不要忘记第二个变量(nextLayer)不能超过列表/元组的长度。

    【讨论】:

      猜你喜欢
      • 2016-03-03
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多