Python - if a key is not in one list, append to another

后端 未结 1 1400
庸人自扰
庸人自扰 2021-01-29 05:52

This is probably a fairly simple one, but I haven\'t figured it out quite right.

I have two lists of tuples

List_A

[(\'a\', 0.033), (\'b\', 0.030),

1条回答
  •  孤城傲影
    2021-01-29 06:44

    Put keys from List_B in a set and then use a simple for loop:

    A = [('a', 0.033), ('b', 0.030), ('c', 0.020), ('d', 0.010), ('e', 0.005)]    
    B = [('a', 0.057), ('b', 0.065), ('w', 0.060), ('x', 0.040), ('y', 0.010)]
    
    B_keys = {k for k, _ in B}
    
    for k, _ in A:
        if k not in B_keys:
            B.append((k, 0.0))
    
    B
    #[('a', 0.057),
    # ('b', 0.065),
    # ('w', 0.06),
    # ('x', 0.04),
    # ('y', 0.01),
    # ('c', 0.0),
    # ('d', 0.0),
    # ('e', 0.0)]
    

    0 讨论(0)
提交回复
热议问题