python匹配列表列表

时间:2012-11-23 20:06:14

标签: list python-3.x

def compare_two_lists(list1,list2):
   i=0
   j=0
   while i < len(list2) :
      if i%2 == 0:
         j == 0
      else:
         j == 1
      for sublist2 in list2[i:] :
         for sublist in list1[j:]:
            #sublist.intersection(sublist2)
            intersect =  [x for x in sublist if x in sublist2]
            print('from set ',sublist, len(intersect),' matched number(s): ', intersect)
            i=i +1

compare_two_lists([[1,2,3,4,5],[20,30]],[[5,3,7,8,1],[20,10],[4,10,1,7,8],[30,20]])

我正在尝试获取列表1的列表0和1以正确比较列表2的列表0,1,2和3并返回匹配。该程序几乎可以工作,因为它确实返回列表中的匹配以及其他迭代。我似乎无法让迭代发生两次并返回[1,3,5],[20], [1,4],[20,30]。请帮忙。我正在疯狂地试图理解如何正确地放置函数并在逻辑上使用循环!!

1 个答案:

答案 0 :(得分:0)

def compare_two_lists(list1,list2):
    lRet = []                         #a
    for i in range(len(list2)):       #b
        j= i%2                        #c
        sublist1 = list1[j]           
        sublist2 = list2[i]           
        lRet.append([x for x in sublist1 if x in sublist2])   
    return lRet 

compare_two_lists([[1,2,3,4,5],[20,30]],[[5,3,7,8,1],[20,10],[4,10,1,7,8],[30,20]])

这似乎可以解决问题。这是一个解释(见上面的行标签):

  • a:lRet已初始化。我们正在建立此变量中的列表列表
  • b:我遍历list2的每个索引
  • c:如果我是偶数则j为零,否则j为1。您的代码中有j==1j==0。这些运算符不会更改任何操作数值。你的意思是j=1等,但这种方式更快

为了解释其余部分,我将通过示例输入列表进行实际迭代:

i = 0(第一次迭代)

j=0 
sublist1 = [1,2,3,4,5]
sublist2 = [5,3,7,8,1]
intersection is [1,3,5]. we APPEND this to lRet. 
thus lRet = [[1,3,5],]

I = 1

j=1
sublist1 = [20,30]
sublist2 = [20,10]
the intersection is [20,]
thus lRet = [[1,3,5],[20]]

I = 3

j=0
sublist1 = [1,2,3,4,5]
sublist2 = [4,10,1,7,8]
etc