简体   繁体   中英

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.'), ('jane','1.2.3.4.'), ('jackie', '2.3.4.10.')...]

and a_list (the main list to be checked against)

   a_list = [('a', '1.2.3.'), ('b', '2.3.'), ('c', '2.3.4.')...]

I'd like a modified output to my original question. I'm unsure of how I'd change the code snippet to solve the same question but to output all possibilities?

eg

 new_list = [ ('edward', '1.2.3.4', '1.2.3'), ('jane', '1.2.3.4.', '1.2.3'), ('jackie', '2.3.4.10.', '2.3.'), ('jackie', '2.3.4.10.', '2.3.4')] 

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

You can use list comprehension if you want:

res = [(name, digits, match) for name, digits in e_list 
                             for _, match in 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():
    for name, digits in e_list:
       for _, match in a_list:
           if digits.startswith(match):
              yield name, digits, match

print list(get_res())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM