[英]Python: matching values from one list to the sequence of values in another list
[英]Python: matching values from one list to the sequences of values in another list
在这里询问并回答了我的原始问题: Python:将一个列表中的值匹配到另一个列表中的值序列
我有两个清单。
e_list = [('edward', '1.2.3.4.'), ('jane','1.2.3.4.'), ('jackie', '2.3.4.10.')...]
和a_list(要检查的主要列表)
a_list = [('a', '1.2.3.'), ('b', '2.3.'), ('c', '2.3.4.')...]
我想要原始问题的修改输出。 我不确定如何更改代码片段来解决相同的问题,但要输出所有可能性?
例如
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')]
您需要遍历a_list
所有内容,然后处理在e_list
中添加值的额外情况。 最终看起来像这样:
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)
请在此处查看实际操作: http : //ideone.com/y8uAvC
如果需要,可以使用列表推导:
res = [(name, digits, match) for name, digits in e_list
for _, match in a_list
if digits.startswith(match)]
print res
但是由于它变得复杂,嵌套循环可能更干净。 您可以使用yield
获得最终列表:
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.