[英]Python - Returning the value if there is an “exact” match?
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)
在上面的代碼中,結果是:
'a'
'aa'
我希望結果是:
'a'
使用any()
獲得正確結果的正確方法是什么?
根據我對您的問題的解釋,您似乎想查找key
中的哪個項目在lst
。 這將是這樣做的方式:
def findexact(lst):
key = ['a','g','t']
for k in key:
if k in lst:
print k
return k
您不需要做所有的索引工作。
def findexact(lst):
key = ['a','g','t']
for item in (set(key) & set(lst)):
return item
最簡單的方法是使用Python的內置集合交集:
lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']
key = ['a','g','t']
for item in set(lst).intersection(key):
print item
輸出量
a
將其放入返回完全匹配項的函數中:
def findexact(lst):
key = ['a','g','t']
return set(lst).intersect(key)
或進入至少有一個完全匹配項的返回True
的函數中:
def findexact(lst):
key = ['a','g','t']
return bool(set(lst).intersect(key))
lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']
def findexact(lst):
i=0
key = ['a','g','t']
for eachItm in lst:
if eachItm in key:
print eachItm
findexact(lst)
這應該做你想做的
這個:
item in lst[i] for item in key
在列表的每個元素內查找鍵的每個元素。 並在“ a”內部和“ aa”內部找到“ a”。 它不在lst的任何元素內找到“ g”或“ t”。
為了配合您的預期輸出,則不能使用set.intersection
作為集合是無序的 ,所以如果你得到a
作為第一個項目是完全偶然的機會,你應該做key
一組,並使用in
,遍歷列表返回的第一個匹配這將保持順序:
def findexact(lst):
key = {'a','g','t'}
for ele in lst:
if ele in key:
return ele
return False
如果要獲取所有匹配項並查看非匹配項,只需將鍵設為一組並使用循環即可:
def findexact(lst):
key = {'a','g','t'}
for ele in lst:
if ele in key:
print(ele)
else:
# do whatever
如果要基於是否存在任何公共元素返回布爾值,請使用set.isdisjoint
:
def findexact(lst):
key = {'a','g','t'}
return not key.isdisjoint(lst)
如果至少有一個匹配項,則該函數將返回True,否則將返回不相關的集合,因此它將返回False。
如果要使用索引,請使用枚舉:
def findexact(lst):
key = {'a','g','t'}
for ind,ele in enumerate(lst):
if ele in key:
return ind, ele
return False
如果我們有一個匹配項,它將返回元素和索引,如果您只希望索引僅返回ind
,則沒有匹配項,我們只是返回False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.