简体   繁体   English

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

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

Let's say I have a list of lists like 假设我有一个清单清单

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

I'd like to do something like 我想做类似的事情

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

and I'd like 我想要

n==2

because indeed, 因为确实

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

I hope this example makes my point, I want to find if a list of lists contains a certain list without especifying the full list to be found. 我希望这个例子能说明我的意思,我想查找列表列表是否包含某个列表,而不指定要查找的完整列表。

Approach this in two steps: 分两个步骤进行处理:

  1. Define a function that compares a list against a partial list. 定义将列表与部分列表进行比较的函数。 You can use None instead of the colon from your example. 您可以在示例中使用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. Then loop over the list of lists, calling the function from 1. on each element, until you find an item that matches or the list ends. 然后循环遍历列表列表,在每个元素上从1.调用函数,直到找到匹配的项目或列表结束。

This function should do it (quick&dirty): 这个函数应该做到(快速&肮脏):

>>> 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])

One can define a partial "match" function where None matches all and then use next to find the first partial match (similar to what index does, finding only the first match): 可以定义一个部分“匹配”函数,其中“ 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

In one line: 一行:

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

(assuming that all lists have the same length) (假设所有列表的长度相同)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM