![](/img/trans.png)
[英]Check whether the elements of a column with list values are present in another list
[英]Check whether an entry present in python list and add the elements
我有兩個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)]
我需要檢查list1中是否存在list2中的每個條目。 如果存在,則添加整數部分並存儲在新列表中。 如果不存在,則將該條目添加到新創建的列表中。 所以在這里我新創建的list3應該看起來像
list3 = [('TGFB1', 'TGFB1', 1), ('TGFB1', 'CRP', 0.8),('BRCA2', 'TP53', 0.6),('BRCA1', 'TP53', 2) ]
根據我的上述評論,這可能是您想要的:
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
如果您確實想翻開d3
則返回具有相同結構的列表,請使用:
list3 = [key + (value,) for key, value in d3.iteritems()]
這是我經常做的事情的更復雜的版本。 通常,我不在乎順序,只是把東西扔進字典。 有時我會按鍵排序,因此初始順序無關緊要。
怎么樣一個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.