【问题标题】:Get the index of the exact match from a list从列表中获取完全匹配的索引
【发布时间】:2015-11-10 18:18:36
【问题描述】:
lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']

def findexact(lst):
    i=0
    key = ['a','g','t']
    while i < len(lst):
        if any(item in lst[i] for item in key):
            print i

        i+=1

findexact(lst)

在上面的代码中,结果是:

0
3

我希望结果是:

0

我想获得“精确”匹配的索引。我需要做什么才能获得可接受的结果?

【问题讨论】:

标签: python string indexing find match


【解决方案1】:

尝试将if any(item in lst[i] for item in key): 更改为:

if any(item == lst[i] for item in key):

您得到了多个结果,因为 'a' 是 in 'aa' 但 'a' 不是 == 到 'aa'。

这会给你想要的行为吗?

【讨论】:

  • 如此简单。我喜欢你的回答。我不知道为什么我以前没有想到这一点。
【解决方案2】:

只需使用index()。这会告诉您给定 list 中给定项目的索引。如果它不存在,它会产生一个错误,我们将捕获它。

lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']

def findexact(lst):
    keys = ['a','g','t']
    for key in keys:
        try:
            return lst.index(key)
        except ValueError:
            pass

print findexact(lst)

【讨论】:

    【解决方案3】:

    只需将in 更改为== 并使测试有点不同,如下所示:

    lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']
    
    def findexact(lst):
        key = ['a','g','t']
        for idx, elem in enumerate(lst):
            if any(item == elem for item in key):
                print idx
    
    findexact(lst)
    

    请注意,我直接迭代lst 并从枚举中获取索引。这是一种比引入仅跟踪索引的变量i 更pythonic 的方法。您可以进一步浓缩这一点,因为其他答案中的一个衬里显示。

    【讨论】:

      【解决方案4】:

      您可以将 enumerate 与 gen exp 一起使用,使用默认值调用 next 以捕获您没有公共元素的地方:

      def findexact(lst):
          key = {'a','g','t'}
          return next((ind for ind,ele in enumerate(lst) if ele in key), None)
      lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']
      match = findexact(lst)
      if match is not None:
        print(match)
      0
      

      这是O(n),因为集合查找是O(1),在最坏的情况下,我们查看lst中的每个元素,对于大量数据,使用list.index或将键作为列表并使用in是不会很好地扩展

      【讨论】:

        猜你喜欢
        • 2020-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-14
        • 1970-01-01
        相关资源
        最近更新 更多