函数定义:匹配两个输入列表

Function Definition: Matching two input lists

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 的较长版本第二个列表,如何让我的代码执行此操作?

试试这个:

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

输出:

['543242', '43299919']

如果你有一个大列表,这会表现得更好

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)