2015-10-17 49 views
-1
def match_numbers (nlist, nlist1): 
    '''Returns the integer string whose first three numbers are on the first list''' 
    for x in nlist: 
    for x in nlist1: 
     print(x) 

因此,假设第一列表为['543', '432']和第二列表有['543242', '43299919', '2322242', '245533'],我需要的功能相匹配543432与第二列表上的加长版本,我怎样才能得到我的代码做到这一点?功能定义:匹配两个输入列出

回答

0

如果你有一个大名单,这将执行稍好

list1 = ['543', '432'] 
list2 = ['543242', '43299919', '2322242', '245533'] 

def match_numbers (nlist, nlist1): 
    results = {} 
    for x in nlist1: 
     results.setdefault(x[0:3], []) 
     results[x[0:3]].append(x) 

    for x in nlist: 
     if x in results: 
      print results[x] 


match_numbers(list1, list2) 
0

试试这个:

[x for x in a for i in b if i == x[:len(i)]] 

输出:

[ '543242', '43299919']