Python - 返回值,如果有一个“确切”比赛? [英] Python - Returning the value if there is an "exact" match?

查看:173
本文介绍了Python - 返回值,如果有一个“确切”比赛?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

def findexact lst):
i = 0
key = ['a','g','t']
while I< len(lst):
(如果有的话)(lst [i]中item中key的值):
print lst [i]
i + = 1

findexact lst)

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

 'a'
'aa'

我希望得到的结果是:

pre $ a
code>

使用 any()获得正确结果的正确方法是? / p>

解决方案

要匹配您的预期输出,您不能使用 set.intersection 集合是 unordered ,所以如果你得到 a 作为第一个项目,那么你应该使 key code>一个集合,在中使用,迭代列表返回第一个匹配,以保持顺序:

  def findexact(lst):
key = {'a','g','t'}
for lst:
如果在关键元素:
返回ele
返回False

如果您想获得所有匹配并查看不匹配

  def findexact(lst):
key = {'a' ,'g','t'}
for ele:
如果ele中的键:
print(ele)
else:
#做任何

如果您想根据是否有任何公共元素使用设置返回一个bool .isdisjoint

  def findexact(lst):
key = {'a' ,'g','t'}
return not key.isdisjoint(lst)

如果至少有一个匹配,则该函数将返回True,否则该集合将不相交,因此它将返回False。

如果您希望索引使用枚举:

  def findexact(lst):
key = {'a','g','t'}
表示ind,ele表示枚举(lst):
如果在关键的元素:
返回ind,ele
返回False

返回元素和索引如果我们有一个匹配,如果你只是想索引返回 ind ,没有匹配,我们只是返回False


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 lst[i]
        i+=1

findexact(lst)

in the above code, the result comes out to be:

'a'
'aa'

I would like the result to be:

'a'

What is the right way to use any() to get the right result?

解决方案

To match your expected output, you cannot use set.intersection as sets are unordered so if you get a as the first item it is totally by chance , you should make key a set and use in,iterating over the list returning the first match which will keep the order:

def findexact(lst):
    key = {'a','g','t'}
    for ele in lst:
        if ele in key:
            return ele
    return False

If you want to get all the matches and see the non matches just make key a set and use a loop:

def findexact(lst):
    key = {'a','g','t'}
    for ele in lst:
        if ele in key:
            print(ele)
        else:
            # do whatever

If you want to return a bool based on whether there are any common element use set.isdisjoint:

def findexact(lst):
    key = {'a','g','t'}
    return not key.isdisjoint(lst)

If there is at least one match, the function will return True, if not then the sets are disjoint so it will return False.

If you want the index use enumerate:

def findexact(lst):
    key = {'a','g','t'}
    for ind,ele in enumerate(lst):
        if ele in key:
            return ind, ele
    return False

That will return both the element and the index if we have a match, if you just want the index just return ind, for no match we simply return False

这篇关于Python - 返回值,如果有一个“确切”比赛?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆