Skip to content Skip to sidebar Skip to footer

Python: Matching Values From One List To The Sequences Of Values In Another List

My original question was asked and answered here: Python: matching values from one list to the sequence of values in another list I have two lists. e_list = [('edward', '1.2.3.4

Solution 1:

You need to loop over everything in a_list then deal with the extra case of adding the value in e_list. It ends up looking something like this:

results = []
for name, x in e_list:
    this_name = [name, x]
    for a, b in a_list:
        if x.startswith(b):
            this_name.append(b)
    results.append(tuple(this_name))

print(results)

see this in action here: http://ideone.com/y8uAvC

Solution 2:

You can use list comprehension if you want:

res = [(name, digits, match) forname, digits in e_list 
                             for_, matchin a_list 
                             if digits.startswith(match)]
print res

But since it gets complicated, nested loops may be cleaner. You can use yield to get final list:

def get_res():
    forname, digits in e_list:
       for_, matchin a_list:
           if digits.startswith(match):
              yield name, digits, match

print list(get_res())

Post a Comment for "Python: Matching Values From One List To The Sequences Of Values In Another List"