繁体   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