【问题标题】:Better way to return the index of an element from a list, with element BEHIND preferred [duplicate]从列表中返回元素索引的更好方法,首选元素 BEHIND [重复]
【发布时间】:2020-12-27 22:52:45
【问题描述】:

例如,有一个列表:

numbers = [1,2,3,4,2,1]
print(numbers.index(1))

输出是 0

优先选择后面的元素表示,应该打印末尾“1”的索引,而不是开头的“1”。 IE。 输出应该是5

下面提供了“反转列表”的基线方法,是否有更快更简单的方法来做到这一点?

numbers = [1,2,3,4,2,1]
numbers.reverse()
output = []
for i in range(1,4):
    inv_inx= len(numbers)-numbers.index(i)-1
    output.append(inv_inx)
print(output)
assert output == [5, 4, 2]

【问题讨论】:

    标签: python list indexing


    【解决方案1】:

    一种不会产生任何临时lists 的方法,从末尾开始扫描(因此它不会找到您不关心的所有1s)和短路(因此当它停止时)找到元素)是将生成器表达式与nextreversedenumerate 内置函数组合起来:

    def rindex(seq, value):
        return len(seq) - next(i for i, x in enumerate(reversed(seq), 1) if x == value)
    

    如果找不到该值,这将引发StopIteration,如果你想让它引发ValueError,你只需要转换它:

    def rindex(seq, value):
        try:
            return len(seq) - next(i for i, x in enumerate(reversed(seq), 1) if x == value)
        except StopIteration:
            raise ValueError(f"{value!r} is not in {type(seq).__name__}")  # Rough equivalent to list.index message
    

    为了比较,没有生成器表达式或next 的版本如下所示:

    def rindex(seq, value):
        for i, x in enumerate(reversed(seq), 1):
            if x == value:
                return len(seq) - i
        raise ValueError(f"{value!r} is not in {type(seq).__name__}")
    

    【讨论】:

      【解决方案2】:

      您可以从列表末尾开始搜索:

      列表index() 方法最多可以接受三个参数:

      element - 要搜索的元素

      开始(可选)- 从该索引开始搜索

      end(可选)- 搜索直到该索引的元素

      numbers = [1,2,3,4,2,1]
      print(numbers.index(1,-1))
      

      输出:

      5
      

      编辑:

      如果搜索项不在列表末尾:

      lst = [1,2,3,4,2,1,2]
      
      print(len(lst)-1 - lst[::-1].index(1))   # 5
      

      Source

      【讨论】:

      • @Chris 点了。将编辑。
      【解决方案3】:

      尝试这不是最好的解决方案,而是更好的解决方案。

      numbers = [1,2,1,4,2,1]
      count=0
      for i in numbers :
          count=count+1
          if i == 1:
              a=[]
              a.append(count-1)
      print(a)    #5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-01
        • 2020-12-01
        • 1970-01-01
        • 2018-07-06
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多