【问题标题】:Indexing duplicates python [duplicate]索引重复python [重复]
【发布时间】:2017-11-09 13:04:45
【问题描述】:

如果我在列表中使用 .index ,它将始终返回出现的第一个元素。但是如果它们是重复的并且我也想要它们的索引怎么办? 例如:

listm=["shell","shell","use"]
listm.index("shell")

它将返回 0,但有 2 个 "shell"s。我如何获得两者的索引?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    通过使用enumerate 的列表推导:

    >>> ind = [i for i, j in enumerate(listm) if j == 'shell']
    >>> print(ind)
    [0, 1]
    

    【讨论】:

      【解决方案2】:

      使用:list comprehension + enumerate

      In [26]: listm = ["shell","shell","use"]
      
      In [27]: [i for i,j in enumerate(listm) if j == "shell"]
      Out[27]: [0, 1]
      

      【讨论】:

        猜你喜欢
        • 2019-03-03
        • 2017-12-31
        • 1970-01-01
        • 2014-06-19
        • 2017-09-15
        • 2021-11-02
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        相关资源
        最近更新 更多