【问题标题】:Using .index() with a list that has repeated elements [duplicate]将 .index() 与具有重复元素的列表一起使用 [重复]
【发布时间】:2016-07-30 22:01:37
【问题描述】:

所以我正在检查一个列表并打印所有等于三的值

for item in top:
    if item == 3:
        print('recommendation found at:')
        print(top.index(item))

问题是这只会连续打印第一个值为 3 的元素。如何打印每个值为 3 的元素的位置?

【问题讨论】:

    标签: python


    【解决方案1】:

    使用enumerate

    >>> top = [1, 3, 7, 8, 3, -3, 3, 0]
    >>> hits = (i for i,value in enumerate(top) if value == 3)
    

    这是一个生成器,将生成所有索引i,其中top[i] == 3

    >>> for i in hits:
    ...     print(i)
    ... 
    1
    4
    6
    

    【讨论】:

      【解决方案2】:

      https://docs.python.org/2/tutorial/datastructures.html
      Index: "返回列表中第一个值为 x 的项目的索引。"

      一个简单的解决方案是:

      for i in range(len(top)):
          if top[i] == 3:
              print('recommendation found at: ' + str(i))
      

      【讨论】:

        猜你喜欢
        • 2018-07-19
        • 1970-01-01
        • 2014-02-17
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        • 2011-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多