使用python在字典中保留最长的异构体多个键

2024-05-16 16:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个很长的列表中删除最小的异构体,因为我只想使用最长的。 我的数据如下:

comp30035   seq1    608 
comp30037   seq1    265 
comp3003    seq1    298 
comp30043   seq1    236 
comp30043   seq3    529 
comp30043   seq4    315 
comp30043   seq5    1120    

对于只有一种异构体(例如只有seq1)的contigs,没有问题,但其中许多具有多种异构体(seq2,3…)。例如,对于config comp30043,我只想在我的列表中保留最长的seq5。你知道吗

我只想保留其中最长的一个,显然我需要保留一个只有一个异构体。你知道吗

我在考虑使用python字典,以contigs名称作为键,isoform名称和长度有值,但我没有使用多个值的经验。你知道吗

任何提示和帮助我开始是非常感谢!你知道吗

干杯


Tags: 数据名称config列表contigs异构体seq2seq1
2条回答

一个简单的解决方案是使用元组作为字典的值。或者,您甚至可以使用字典本身作为字典的值。下面是一段代码[可能可读性比效率高],它将完成前者。你知道吗

假设您已将数据保存在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)

希望这有帮助。你知道吗

试试下面的,我会尽量评论一下,这样你就可以很容易地理解了。你知道吗

我使用字典以如下形式存储元素:{"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)

相关问题 更多 >