2015-11-04 65 views
0

我开始写这个奇怪的东西,只是好奇而已。我一直在看可视化器中的代码,它看起来像我期望的迭代,但不输出我认为应该的东西。有人能告诉我我错过了什么吗?这只是SQL连接表处理后的一个有趣例子。Python 3出现匹配

def query(a=[1,2,3,4], b=[3,1,1,2,3,4,5,6]): 
     """ 
     table A   table B   Expected Output  Actual Output 
     idx value  idx value   indxA indxB   indxA indxB 
     0  1   0 3    0  1    0  1 
     1  2   1 1    0  2    0  1 
     2  3   2 1    1  3    1  3 
     3  4   3 2    2  0    2  0 
         5 4    2  3    2  0 
         6 5    3  5    3  5 
         7 6 

     EXAMPLE 
     Table A index 0 occurs at Table B index 1 and 2 
     PROBLEM 
     Anywhere there are multiple matches only first occurrence prints 
     """ 
     for idx, itemA in enumerate(a): 
      if itemA in b: 
       for itemB in b: 
        if itemA == itemB: 
         print("{} {}".format(a.index(itemA), b.index(itemB))) 


    query() 

回答

2

list.index(x)返回的第一项值为x的列表中的索引。 所以你应该使用enumerate(b)

def query(a=[1,2,3,4], b=[3,1,1,2,3,4,5,6]): 
    for index_a, value_a in enumerate(a): 
     for index_b, value_b in enumerate(b): 
      if value_a == value_b: 
       print("{} {}".format(index_a, index_b)) 

query() 
1

大型列表遍历每个元素在一个列表中为对方元素于其他列表中可能会很慢。这是一个二次算法。

这是只有列表的解决方案。我把打印出来,因为它会用大多数的时间,并在列表中返回的结果:

def query_list(a, b): 
    res = [] 
    for index_a, value_a in enumerate(a): 
     for index_b, value_b in enumerate(b): 
      if value_a == value_b: 
       res.append((index_a, index_b)) 
    return res 

这是使用字典的替代实现:

def query_dict(a, b): 
    indices = {value: index for index, value in enumerate(a)} 
    res = [] 
    for index_b, value_b in enumerate(b): 
     if value_b in indices: 
      res.append((indices[value_b], index_b)) 
    return sorted(res) 

生成一些示例数据:

import random 
a = list(range(1, 1000)) 
b = [random.randint(1, 100) for x in range(10000)] 

清单版本:

%timeit query_list(a, b) 
1 loops, best of 3: 1.09 s per loop 

比字典版本慢得多:

%timeit query_dict(a, b) 
100 loops, best of 3: 11.8 ms per loop 

这种关于使用更大的示例数据的10

因子:

import random 
a = list(range(1, 10000)) 
b = [random.randint(1, 100) for x in range(10000)] 

的差异变得更加明显:

%timeit query_list(a, b) 
1 loops, best of 3: 11.4 s per loop 

%timeit query_dict(a, b) 
100 loops, best of 3: 13.7 ms per loop 

接近因子t o 100.

+0

非常有趣!非常感谢。 –