簡體   English   中英

在列表列表中查找不完全匹配

[英]Finding a not exact match in a list of lists

假設我有一個清單清單

    new_list=[[1,2,3],
              [9,1,6],
              [7,3,4]]

我想做類似的事情

    n=new_list.index([7,:,4])

我想要

n==2

因為確實

new_list[2]==[7,3,4]

我希望這個例子能說明我的意思,我想查找列表列表是否包含某個列表,而不指定要查找的完整列表。

分兩個步驟進行處理:

  1. 定義將列表與部分列表進行比較的函數。 您可以在示例中使用None而不是冒號。

     def matches(pattern, candidate): # check that pattern and candidate are lists of same length # loop over all indices i: # if pattern[i] is not None, candidate[i] must be equal 
  2. 然后循環遍歷列表列表,在每個元素上從1.調用函數,直到找到匹配的項目或列表結束。

這個函數應該做到(快速&骯臟):

>>> new_list=[[1,2,3],
...           [9,1,6],
...           [7,3,4]]
>>> 
>>> def find(lst, members):
...   for i in range(len(lst)):
...     match=True
...     for j in members:
...       if j not in lst[i]:
...         match=False
...         break
...     if match:
...       return i
...   return None
... 
>>> find(new_list, [2, 3])
0
>>> find(new_list, [3, 1])
0
>>> find(new_list, [2, 4])
>>> find(new_list, [7, 4])
2
>>> find(new_list, [7])
2
>>> find(new_list, [8, 9])

可以定義一個部分“匹配”函數,其中“ None匹配所有,然后使用next查找第一個部分匹配(類似於index所做的,僅查找第一個匹配):

pMatch = lambda l1, l2: all([x[0] == x[1] or x[0] == None for x in zip(l1, l2)]) 

# examples of partial matches
pMatch([1, 2, None], [1, 2, 3])                                                                                                                                                             
# True
pMatch([1, 2, 4], [1, 2, 3])                                                                                                                                                                
# False

new_list = [[1, 2, 3], [9, 1, 6], [7, 3, 4]]
l = [7, None, 4]

next(i for i in range(len(new_list)) if pMatch(l, new_list[i]))    
# 2

一行:

next(i for i in range(len(new_list)) if all([x[0]==x[1] or x[0]==None for x in zip(l, new_list[i])])) 
# 2

(假設所有列表的長度相同)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM