2012-05-14 56 views
1

我有一系列的基因,我想與屬性的列表和顏色相關聯:地圖兩個列表成爲一個倒置的字典

gene_A_color = red 
gene_B_color = blue 

gene_A_property = ['a','b','c'] 
gene_B_property = ['d','e','f'] 

爲繪製我的目的想創造一個字典在那裏我可以使用屬性值爲重點,以獲得無論是顏色或基因如下:

#lookup dictionary 
{'a': ['red', 'gene_A'] 
'b': ['red', 'gene_A'] 
'c': ['red', 'gene_A'] 
'd': ['blue' 'gene_B'] 
'e': ['blue' 'gene_B'] 
'f': ['blue' 'gene_B']} 
lookup[a][0] = red 
lookup[a][1] = gene_A 

我開始時是這樣,但如果我失去了基因名稱只能反轉列表:

lookup_dict = defaultdict(list) 
    lookup_dict['red'] = ['a','b','c'] 
    lookup_dict['blue'] = ['d','e','f'] 
inverted = defaultdict(list) 
for k, v in lookup_dict.items(): 
    inverted[v].append(k) 

#inverted 
{'a': 'red' 
'b': 'red' 
'c': 'red' 
'd': 'blue' 
'e': 'blue' 
'f': 'blue' } 

意見建議?

回答

6

你已經擁有了你需要的一切,基因與屬性的聯繫。其他的只是一種自我解決。

爲什麼不使用類來表示基因?

class Gene(object): 
    def __init__(self, color, properties): 
     self.color = color 
     self.properties = properties 

geneA = Gene('red', ['a', 'b', 'c']) 
geneB = Gene('blue', ['d', 'e', 'f']) 
genes = [geneA, geneB] 

inverted = {} 
for gene in genes: 
    for prop in gene.properties: 
     inverted[prop] = gene.color 
+0

良好的通話。我可以讓這個類也有gene.name,並做倒置[prop] = [gene.color,gene.name]謝謝! – zach

1

如果你只是想幾個簡單的語句來做到這一點:

>>> gene_A_property = ['a','b','c'] 
>>> gene_B_property = ['d','e','f'] 
>>> ld={k:['red','gene_A'] for k in gene_A_property} 
>>> ld.update({k:['blue','gene_B'] for k in gene_B_property}) 
>>> ld 
{ 'a': ['red', 'gene_A'], 
    'c': ['red', 'gene_A'], 
    'b': ['red', 'gene_A'], 
    'e': ['blue', 'gene_B'], 
    'd': ['blue', 'gene_B'], 
    'f': ['blue', 'gene_B'] 
}