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

时间:2019-06-08 06:32:55

标签: python

假设我有一个类似列表的列表

    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]

我希望这个例子能说明我的意思,我想确定列表列表中是否包含某个列表,而不指定要查找的完整列表。

3 个答案:

答案 0 :(得分:0)

分两个步骤进行处理:

  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.开始调用函数,直到找到匹配的项目或列表结束。

答案 1 :(得分:0)

此函数应该执行此操作(快速&肮脏):

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

答案 2 :(得分:0)

可以定义部分“匹配”功能,其中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

(假设所有列表的长度都相同)