我试图从一个非常长的列表中删除最小的异构体,因为我只想使用最长的。我的数据如下所示:
comp30035 seq1 608
comp30037 seq1 265
comp3003 seq1 298
comp30043 seq1 236
comp30043 seq3 529
comp30043 seq4 315
comp30043 seq5 1120
对于只有一个异构体(例如,仅seq1)的连续体,没有问题,但它们中的许多都有许多异构体(seq1 2,3…)。。例如,对于配置comp30043,我只想在我的列表中保留最长的seq5。
我只想保留其中最长的一个,很明显,我需要保留一个只有一个等价物的。
我正在考虑使用python字典,将contigs名称作为键,异构体名称和长度有值,但我没有使用多个值的经验。
任何提示和帮助使我开始是非常感谢!
干杯
发布于 2014-01-13 04:43:08
一个简单的解决方案是使用元组作为字典的值。或者,您甚至可以使用字典本身作为一个值。这里有一个代码片段,它的可读性可能比效率更高,这将实现前者。
假设您已经将数据保存在contigsFile.txt中:
contigDict = {}
for line in open('contigsFile.txt'):
contigId, isoform, length = line.split()
if contigId in contigDict:
curr_Isoform, curr_length = contigDict[contigId]
if int(curr_length) < int(length):
contigDict[contigId] = (isoform, length)
else:
contigDict[contigId] = (isoform, length)
希望这能有所帮助。
发布于 2014-01-13 04:35:29
尝试下面,我会尝试评论它,这样你就可以很容易地理解它。
我使用字典将元素存储在表单:{"compxxxx" : ("seqx", number)}
中。
with open("sample.txt", 'r') as f:
lines = [line.split() for line in f] # List of lists, each nested list contains strings
result = {} # To store result
for l in lines: # For each nested list
if l[0] not in result: # If the 'key'(compxxxx) is not in 'result'
result[l[0]] = (l[1], int(l[2])) # Add elements to 'result'. Note the int cast of the 'number'
elif l[2] > result[l[0]][1]: # If 'key' is in 'result' check if 'number' is higher
result[l[0]] = (l[1], int(l[2]))
for k, v in result.iteritems(): # To print elements
print k, v
输出:
comp30035 ('seq1', 608)
comp30043 ('seq5', 1120)
comp30037 ('seq1', 265)
comp3003 ('seq1', 298)
https://stackoverflow.com/questions/21083791
复制相似问题