根据楼主的代码,依葫芦画瓢写了一段,也是第一次知道字典原来也能排序。然后也附上自己思路写的一段代码,仅供参考,因为不太熟悉一些python包,所以用嵌套列表解决的排序问题。
楼主代码练习:
[Python] 纯文本查看 复制代码 #!/usr/bin/env python
#_*_ coding: utf-8 _*
from operator import itemgetter
from collections import OrderedDict
#创建一个有序字典集合,根据输入的先后顺序排序
seqTest = OrderedDict()
gcCountent = OrderedDict()
with open('E:\\bioinfo\study\data\\test5.txt','r') as input_file:
#逐行读取输入文件
for line in input_file:
line = line.rstrip() #删除字符串末尾的指定字符,默认为空格
#将DNA序列信息保存在有序字典seqTest中
if line.startswith('>'):
seqName = line.strip('> ')
else:
seqTest[seqName] = line
for key, value in seqTest.items():
#生成一个包含GC含量的有序字典
seq_length = len(value)
GC_ratio = (float(value.count('C') + value.count('G'))) / seq_length
gcCountent[key] = GC_ratio
#将字典排序,根据每个元祖中的第二个元素排序
#将字典排序完之后,其形式也不为字典格式
gcCountent_sort = sorted(gcCountent.items(), key=itemgetter(1))
#取最大GC比
large_Name = gcCountent_sort[-1][0]
large_GCRation = gcCountent_sort[-1][1]
print 'GC比最大的DNA序列为:\n%s\n%.6f' % (large_Name, large_GCRation)
我的代码:
[Python] 纯文本查看 复制代码 #!/usr/bin/env python
#_*_ coding: utf-8 _*
gcCount = []
def seq_GCRatio(sequence):
#输入含有序列信息的字符串,输出该序列中的GC比
GC_count = float(sequence.count('C') + sequence.count('G'))
seq_length = len(sequence)
GC_ratio = GC_count / seq_length * 100
return GC_ratio
with open('E:\\bioinfo\study\data\\test5.txt', 'r') as input_file:
for line in input_file:
seq_list = []
if line.startswith('>'):
seq_name = line.strip('[> | \n]')
else:
sequence = line.strip()
GC_ratio = seq_GCRatio(sequence)
seq_list.append(seq_name)
seq_list.append(GC_ratio)
gcCount.append(seq_list)
GC_Ratio_sort = sorted(gcCount, key=lambda x:x[1])
print 'GC比最高的序列为:\n%s\n%.6f' % (GC_Ratio_sort[-1][0], GC_Ratio_sort[-1][1])
|