功能定义:匹配两个输入列表

时间:2015-10-17 01:33:38

标签: python function input definition

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与其较长版本匹配的函数列表,如何让我的代码执行此操作?

2 个答案:

答案 0 :(得分:0)

试试这个:

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

输出:

  

['543242','43299919']

答案 1 :(得分: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)
相关问题