-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)

So suppose the first list was ['543', '432'] and the second list had ['543242', '43299919', '2322242', '245533'], and I need the function to match 543 and 432 with its longer version on the second list, how can I get my code to do this?

sam
  • 2,033
  • 2
  • 10
  • 13
Deer530
  • 73
  • 1
  • 1
  • 10

2 Answers2

0

Try this:

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

Output:

['543242', '43299919']

sam
  • 2,033
  • 2
  • 10
  • 13
0

If you have a large list, this will perform slightly better

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)
Javier Buzzi
  • 6,296
  • 36
  • 50