Python:将一个列表中的值匹配到另一个列表中的值序列 [英] Python: matching values from one list to the sequences of values in another list

查看:1036
本文介绍了Python:将一个列表中的值匹配到另一个列表中的值序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里询问并回答了我的原始问题:

My original question was asked and answered here: Python: matching values from one list to the sequence of values in another list

我有两个列表.

   e_list = [('edward', '1.2.3.4.'), ('jane','1.2.3.4.'), ('jackie', '2.3.4.10.')...]

和a_list(要检查的主要列表)

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?

例如

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

这篇关于Python:将一个列表中的值匹配到另一个列表中的值序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆