且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:将一个列表中的值匹配到另一个列表中的值序列

更新时间:2022-05-05 23:02:25

如果需要,可以使用列表理解:

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

但是,由于它变得复杂,嵌套循环可能更干净.您可以使用yield获取最终列表:

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