我一直在研究一个程序,我在编程时遇到了问题。
这是我的代码:
dict=([{'geneA': [10, 20]}, {'geneB': [12, 45]}, {'geneC': [36, 50]}],
[{'geneD': [45, 90]}, {'geneT': [100, 200]}],
[{'geneF': [15, 25]}, {'geneX': [67, 200]}, {'GeneZ': [234, 384]}])
所以我基本上设置的dict等于染色体1,2和3的数据。 有没有什么方法可以在dict中显示这三个字符串的名称而不将其作为dict索引的一部分?
答案 0 :(得分:1)
这里的主要问题是您没有声明dictionary而是tuple。
尝试:
>> dict= {
'chromosome1' : [{'geneA': [10, 20]}, {'geneB': [12, 45]}, {'geneC': [36, 50]}],
'chromosome2' : [{'geneD': [45, 90]}, {'geneT': [100, 200]}],
'chromosome3' : [{'geneF': [15, 25]}, {'geneX': [67, 200]}, {'GeneZ': [234, 384]}]
}
>> print(dict['chromosome1'])
[{'geneA': [10, 20]}, {'geneB': [12, 45]}, {'geneC': [36, 50]}]
>> print(dict['chromosome2'])
[{'geneD': [45, 90]}, {'geneT': [100, 200]}]
>> print(dict['chromosome3'])
[{'geneF': [15, 25]}, {'geneX': [67, 200]}, {'GeneZ': [234, 384]}]
您也可以尝试POO方法。如果你实现了几个类,如下所示:
class Gene:
def __init__(self, name, data):
self.name = name
self.data = data
def __getitem__(self, index):
return self.data[index]
class Chromosome:
def __init__(self, name, data):
self.name = name
self.data = data
def __getitem__(self, index):
return self.data[index]
您将能够编写如下代码:
chromosome1 = Chromosome("chromosome1", [
Gene('geneA', [10, 20]),
Gene('geneB', [12, 45]),
Gene('geneC', [36, 50])
])
并且认为如下:
print(chromosome1.name) # Print the chromosome name
>>> chromosome1
print(chromosome1[0].name) # The name of the first gene
>>> geneA
print(chromosome1[1].name) # The name of the second gene
>>> geneB
print(chromosome1[0][1]) # The second value of the first gene
20
你也可以有一个choromosomes列表(这实际上是你想要的):
lchrom = [chromosome1, ...]
print(lchrom[0][1]) # The second gene of the first choromosome in the list. (geneB)
print(lchrom[0][1][0]) # The first value second gene of the first choromosome in the list. (12)