python:按键搜索嵌套列表并将其存储到嵌套列表中

时间:2015-09-13 02:02:12

标签: python list python-2.7 python-3.x

我有一个嵌套列表,如:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>

我有一个参考嵌套列表,如:

list1 = [(A,0.75),(D,0.49),(Y,0.36)]
  1. 我想在主列表中搜索关键元素A.
  2. 在主列表中找到A后,将相应的键,值对存储在新的嵌套列表中。
  3. 对D和Y重复1和2.(list1中的所有元素)
  4. 我希望输出为:

    mainlist = [(A,10),(B,20),(C,30),(D,40),(E,50).........,(Y,250),(Z,260)]
    

1 个答案:

答案 0 :(得分:2)

你在寻找这样的东西:

list1 = [('A',0.75),('D',0.49),('Y',0.36)]
mainlist = [('A',10),('B',20),('C',30),('D',40),('E',50),('Y',250),('Z',260)]

keys = {k[0] for k in list1} # create a set with keys from list1
newlist = [k for k in mainlist if k[0] in keys] # get items from mainlist with good keys 
print(newlist)

输出:

[('A', 10), ('D', 40), ('Y', 250)]