Python:将一个列表中的值匹配到另一列表中的值序列 [英] Python: matching values from one list to the sequence of values in another list
问题描述
真的需要帮助.我对循环感到困惑,撞到了砖墙.
Really need help. I've confused myself with loops and hit a brick wall.
我有两个列表.
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.')...]
我的问题:我想将 e_list 中数字的数字与 a_list 中数字的最短序列进行匹配.这样, new_list 的格式应类似于:
My problem: I want to match the digits in the numbers in e_list to the shortest sequence of the numbers in a_list. So that new_list is formed to look like:
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.')...]
我目前所做的(不多,我知道)是:
What I've currently done (not much, I know) is:
for e in e_list:
e_key = e[1]
for a in a_list:
a_key = a[1]
if a_key in e_key:
print a_key, "in"
这是在检查 a_list 的编号是否在 e_list 的编号中.但是然后它为所有序列打印出输入",例如对于b和c,jackie都计入in,而我希望它是最短的值b.我现在正为下一步工作而苦苦挣扎.任何帮助,将不胜感激.预先谢谢你.
What this is doing is checking if the numbers of a_list are in those of e_list. But then it's printing out "in" for all sequences e.g. jackie is counted as in for both b and c, whereas I want it to be the shortest value, b. I'm struggling now with what the next step is. Any help would be appreciated. Thankyou in advance.
推荐答案
for name, digits in e_list:
shortest = sorted([d for l, d in a_list if digits.startswith(d)], key=len)[0]
print name, digits, shortest
这篇关于Python:将一个列表中的值匹配到另一列表中的值序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!