【问题标题】:Python: finding an element in a list [duplicate]Python:在列表中查找元素[重复]
【发布时间】:2010-10-10 22:14:58
【问题描述】:

在 Python 中查找列表中元素索引的好方法是什么?
请注意,列表可能未排序。

有没有办法指定使用什么比较运算符?

【问题讨论】:

  • 可以取消将此标记为重复,问题和答案不处理符合条件的类实例的情况。
  • 另外,在列表中查找项目的索引与在列表中查找项目是不同的。

标签: python list


【解决方案1】:

index 方法,i = array.index(value),但我认为您不能指定自定义比较运算符。不过,编写自己的函数来做到这一点并不难:

def custom_index(array, compare_function):
    for i, v in enumerate(array):
        if compare_function(v):
            return i

【讨论】:

    【解决方案2】:

    最好的方法可能是使用list method .index

    对于列表中的对象,您可以执行以下操作:

    def __eq__(self, other):
        return self.Value == other.Value
    

    您需要的任何特殊处理。

    你也可以在 enumerate(arr) 中使用 for/in 语句

    查找值 > 100 的项目的索引的示例。

    for index, item in enumerate(arr):
        if item > 100:
            return index, item
    

    Source

    【讨论】:

      【解决方案3】:

      来自Dive Into Python

      >>> li
      ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
      >>> li.index("example")
      5
      

      【讨论】:

      • 但是当元素不在列表中时,此代码会出错。在当前示例上下文中,如果我搜索“三个”(即:li.index('three'))会出错。
      • 您可以捕获错误以检测列表中没有内容的情况。 try: li.index("three") except ValueError: found = false
      • 如果你真的想找到索引,那么首先检查数组中的元素如果为真然后只做 => li.index("example")
      【解决方案4】:

      列表的 index 方法将为您完成此操作。如果要保证顺序,请先使用sorted() 对列表进行排序。 Sorted 接受 cmp 或 key 参数来指示排序方式:

      a = [5, 4, 3]
      print sorted(a).index(5)
      

      或者:

      a = ['one', 'aardvark', 'a']
      print sorted(a, key=len).index('a')
      

      【讨论】:

        【解决方案5】:

        这个怎么样?

        def global_index(lst, test):
            return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )
        

        用法:

        >>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
        <generator object <genexpr> at ...>
        >>> list(_)
        [3, 4, 5]
        

        【讨论】:

        • 获取pythonic: def global_index(lst, test): return (idx for idx, val in enumerate(lst) if test(val) )
        • 过滤器(lambda x: x>3, [1,2,3,4,5,6])
        【解决方案6】:

        这是使用列表推导的另一种方式(有些人可能会觉得它值得商榷)。它对于简单的测试非常平易近人,例如对象属性的比较(我需要很多):

        el = [x for x in mylist if x.attr == "foo"][0]
        

        当然,这是假设列表中存在合适的元素(并且实际上是唯一性)。

        【讨论】:

        • el = [x for x in mylist if x.attr == "foo"] if el: do something with el[0] 解决“存在”问题
        • el = next((x for x in mylist if x.attr == "foo"), None) 如果你想在不存在的情况下接收一个值
        【解决方案7】:

        假设你想在一个 numpy 数组中找到一个值, 我想这样的事情可能会起作用:

        Numpy.where(arr=="value")[0]
        

        【讨论】:

        • 如果您要查找特定行,则不适用于多维数组,例如arr = np.array([[0,0,1],[0,1,0],[1,0,0]]) 如果你这样做 np.where(arr == [0,1,0]) 它不会给出正确的结果
        • @ierdna,您不需要提供axis=0axis=1 吗?
        【解决方案8】:

        如果你只是想知道一个元素是否包含在列表中:

        >>> li
        ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
        >>> 'example' in li
        True
        >>> 'damn' in li
        False
        

        【讨论】:

          【解决方案9】:

          我通过改编一些教程找到了这一点。感谢谷歌,感谢你们所有人;)

          def findall(L, test):
              i=0
              indices = []
              while(True):
                  try:
                      # next value in list passing the test
                      nextvalue = filter(test, L[i:])[0]
          
                      # add index of this value in the index list,
                      # by searching the value in L[i:] 
                      indices.append(L.index(nextvalue, i))
          
                      # iterate i, that is the next index from where to search
                      i=indices[-1]+1
                  #when there is no further "good value", filter returns [],
                  # hence there is an out of range exeption
                  except IndexError:
                      return indices
          

          一个非常简单的用法:

          a = [0,0,2,1]
          ind = findall(a, lambda x:x>0))
          
          [2, 3]
          

          附:怀疑我的英语

          【讨论】:

            【解决方案10】:

            我使用函数返回匹配元素的索引(Python 2.6):

            def index(l, f):
                 return next((i for i in xrange(len(l)) if f(l[i])), None)
            

            然后通过 lambda 函数使用它来通过任何所需的方程式检索所需的元素,例如通过使用元素名称。

            element = mylist[index(mylist, lambda item: item["name"] == "my name")]
            

            如果我需要在代码中的多个位置使用它,我只需定义特定的查找函数,例如按名称查找元素:

            def find_name(l, name):
                 return l[index(l, lambda item: item["name"] == name)]
            

            然后它非常简单易读:

            element = find_name(mylist,"my name")
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2022-08-09
              • 2014-04-21
              • 2015-08-08
              • 2021-01-01
              • 2014-01-08
              • 2016-01-11
              • 2019-02-21
              • 1970-01-01
              相关资源
              最近更新 更多