从lis中获取完全匹配的索引

2024-09-26 22:10:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

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

^{pr2}$

我希望结果是:

0

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


Tags: keyinforlenifdefanyitem
3条回答

只需使用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更改为==,并使测试稍有不同,如下所示:

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风格的方法。你可以进一步浓缩这一点,正如其他答案中的一句话所示。在

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

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

您得到了多个结果,因为“a”是in“aa”,而“a”不是==到“aa”。在

这是你想要的行为吗?在

相关问题 更多 >

    热门问题