【问题标题】:looping lists, but skip element on a condition循环列表,但在条件上跳过元素
【发布时间】:2014-08-06 02:49:00
【问题描述】:

我有以下情况,我有一个字符串列表,我像这样循环它:

list = [string1, string2, string3, string4]

for index, item in enumerate(list):

    print(index, item)

现在我想做的是,如果满足特定条件以将循环索引增加 1。如果我要使用传统的数字 for 循环,我知道该怎么做,我只是想知道是否有办法在这种情况下这样做。

非常感谢

【问题讨论】:

  • 你的意思是要跳过下一个元素?
  • 保留偏移量? offset = 0,然后offset += 1,你想增加吗?
  • 基本上是的,我只是不知道如何使用这种类型的 for 循环
  • 可能重复? stackoverflow.com/q/22295901/748858 -- 这些天我投票认为它会自动关闭,所以我要更加小心:-)
  • 我看了很多帖子都没有发现,我怀疑是因为我不知道我在寻找可迭代对象。我为重复道歉。

标签: python python-3.x


【解决方案1】:

这是使用可迭代对象方便的时候:

lst = [string1, string2, string3, string4]  # BTW, `list` is a bad variable name
iterable = iter(lst)
for item in iterable:
    if condition(item):
        skipped = next(iterable, None)
        continue  # it's unclear from your question if you would want to continue or not...
    do_something(item)

【讨论】:

  • 非常感谢,这看起来正是我所需要的。一旦超时,我将标记为已接受。
  • @Jimboid 还要注意变量名是lst,这是因为list是内置的,你不应该把它用作变量名。
  • @BurhanKhalid -- 感谢您解释我的评论背后的为什么 :)
  • 感谢提示,我实际上并没有在代码中这样命名它,但我不知道它是一个内置名称。
  • @Jimboid 文档中提供了2.73.2 的列表。
猜你喜欢
  • 2012-03-02
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
相关资源
最近更新 更多