繁体   English   中英

从列表中获得完全匹配的索引

[英]Get the index of the exact match from a list

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

我想获取“完全匹配”的索引。 我需要怎么做才能获得可接受的结果?

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

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

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

那给你想要的行为吗?

只要改变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相比,这是一种更加Python化的方法。 正如其他答案中的一个衬里所示,您可以进一步压缩。

只需使用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)

您可以将gen exp与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) ,在最坏的情况下,我们使用list.index或将键作为列表,而使用in不会查看lst中的每个元素,以获取大量数据很好地缩放

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM