从列表中获取完全匹配的索引
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
我想获取 "exact" 匹配项的索引。我需要做什么才能获得可接受的结果?
只需将 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 的方式。您可以将其进一步压缩,如其他答案中的一行所示。
尝试将 if any(item in lst[i] for item in key):
更改为:
if any(item == lst[i] for item in key):
您得到了多个结果,因为 'a' 是 in
'aa' 但 'a' 不是 ==
到 'aa'。
这会给你想要的行为吗?
只需使用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)
您可以将 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
不会很好地扩展
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
我想获取 "exact" 匹配项的索引。我需要做什么才能获得可接受的结果?
只需将 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 的方式。您可以将其进一步压缩,如其他答案中的一行所示。
尝试将 if any(item in lst[i] for item in key):
更改为:
if any(item == lst[i] for item in key):
您得到了多个结果,因为 'a' 是 in
'aa' 但 'a' 不是 ==
到 'aa'。
这会给你想要的行为吗?
只需使用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)
您可以将 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
不会很好地扩展