2024-09-26 22:10:46 发布
网友
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
我想得到“精确”匹配的索引。我需要做什么才能得到可接受的结果?在
只需使用index()。这将告诉您给定list中给定项的索引。如果它不存在,它会产生一个错误,我们将捕捉到它。在
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)
只需将in更改为==,并使测试稍有不同,如下所示:
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,并从enumerate获取索引。这是一种比引入一个只跟踪索引的变量i更具python风格的方法。你可以进一步浓缩这一点,正如其他答案中的一句话所示。在
lst
i
尝试将if any(item in lst[i] for item in key):更改为:
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
中给定项的索引。如果它不存在,它会产生一个错误,我们将捕捉到它。在只需将
in
更改为==
,并使测试稍有不同,如下所示:请注意,我正在直接迭代
lst
,并从enumerate获取索引。这是一种比引入一个只跟踪索引的变量i
更具python风格的方法。你可以进一步浓缩这一点,正如其他答案中的一句话所示。在尝试将
if any(item in lst[i] for item in key):
更改为:您得到了多个结果,因为“a”是
in
“aa”,而“a”不是==
到“aa”。在这是你想要的行为吗?在
相关问题 更多 >
编程相关推荐