简体   繁体   English

检查python列表中是否存在条目并添加元素

[英]Check whether an entry present in python list and add the elements

I have two python list of the form 我有两个python形式的列表

list1 = [('TGFB1', 'TGFB1', 1), ('TGFB1', 'CRP', 0.4),('BRCA2', 'TP53', 0.3)]
list2 = [('BRCA1', 'TP53', 2), ('TGFB1', 'CRP', 0.4),('BRCA2', 'TP53', 0.3)]

I need to check whether each entry in list2 is present in list1 . 我需要检查list1中是否存在list2中的每个条目。 If present add the integer part and store in a new list. 如果存在,则添加整数部分并存储在新列表中。 If not present just append that entry to the newly created list. 如果不存在,则将该条目添加到新创建的列表中。 So here my newly created list3 should look like 所以在这里我新创建的list3应该看起来像

list3 = [('TGFB1', 'TGFB1', 1), ('TGFB1', 'CRP', 0.8),('BRCA2', 'TP53', 0.6),('BRCA1', 'TP53', 2) ]

Following my above comment, this is what you might want: 根据我的上述评论,这可能是您想要的:

from copy import copy

d3 = copy(dict(((x, y), z) for x, y, z in list1))
d2 = dict(((x, y), z) for x, y, z in list2)

for key, value in d2.iteritems():
    d3[key] = (d3[key] if key in d3 else 0.0) + value

If you do really want to turn d3 then back to a list of the same structure use: 如果您确实想翻开d3则返回具有相同结构的列表,请使用:

list3 = [key + (value,) for key, value in d3.iteritems()]

This is a more complicated version of something that I often do. 这是我经常做的事情的更复杂的版本。 Usually, I don't care about order and just throw stuff into a dict. 通常,我不在乎顺序,只是把东西扔进字典。 Or sometimes I order by key so the initial order doesn't matter. 有时我会按键排序,因此初始顺序无关紧要。

How about an OrderedDict (python2.7+): 怎么样一个OrderedDict(python2.7 +):

from collections import OrderedDict

list1 = [('TGFB1', 'TGFB1', 1), ('TGFB1', 'CRP', 0.4),('BRCA2', 'TP53',0.3)]
list2 = [('BRCA1', 'TP53',2), ('TGFB1', 'CRP', 0.4),('BRCA2', 'TP53',0.3)]

d=OrderedDict()
for i in list1:
    d[i[0:2]]=i[2]
for i in list2:
    if i[0:2] in d:
        d[i[0:2]]+=i[2]
    else:
        d[i[0:2]]=i[2]
list3=[k+(v,) for k,v in d.items()]
print(list3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM