【问题标题】:Python - Way to distinguish between item index in a list and item's contents in a FOR loop?Python - 如何区分列表中的项目索引和 FOR 循环中的项目内容?
【发布时间】:2011-04-08 21:10:23
【问题描述】:

例如,如果我想循环遍历一个列表并对除最后一个列表条目之外的所有条目执行一些操作,我可以这样做:

z = [1,2,3,4,2]
for item in z:
    if item != z[-1]:        
        print z.index(item)

但我不会得到输出“...0 1 2 3”,而是得到 “...0 2 3。”

有没有一种方法可以在不使用“for x in range (len(list) - 1)”解决方案的情况下对列表中除最后一项以外的所有项目执行操作(当列表中有相同项目时) ?即,我想继续使用“for item in list”。

非常感谢!

【问题讨论】:

    标签: python list loops for-loop duplicates


    【解决方案1】:

    使用切片:

    for item in z[:-1]:
        # do something
    

    【讨论】:

    • 您可以通过使用 itertools 模块中的 islice 方法来减少创建切片的循环开销,如下所示:for item in itertools.islice(z, 0, len(z)-1):
    【解决方案2】:

    你可以使用:

    for index, item in enumerate(z):
        if index != len(z)-1:
            print index
    

    【讨论】:

    • 或将其与其他答案中建议的切片结合起来:如果您使用 enumarate(z[:-1]) 而不是 enumerate(z) 您可以摆脱 if 声明。
    【解决方案3】:
    for index, item in enumerate(your_list):
        do_something
    

    【讨论】:

      【解决方案4】:

      [z.foo() for z in z[:-1]

      【讨论】:

      • 哇——你们真快。非常感谢(感谢你们所有人)!
      【解决方案5】:
      def all_but_last(iterable):
          iterable= iter(iterable)
      
          try: previous= iterable.next()
          except StopIteration: return
      
          for item in iterable:
              yield previous
              previous= item
      

      把它放在一个模块中,在你需要的地方使用它。

      在你的情况下,你会这样做:

      for item in all_but_last(z):
      

      【讨论】:

        猜你喜欢
        • 2014-09-15
        • 2020-03-12
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多