我有多个像这样的列表:

#Symbol  ID
['AAA','MG_00013']
['AAA','MG_00177']
['AAA','MG_00005']
['BBB','MG_0045']
['BBB','MG_00080']
['CCC','MG_0002'] # and so on...


我想选择ID最小的相同符号的列表。

因此,最终结果是这样的:

#Symbol  ID
['AAA','MG_00005']
['BBB','MG_0045']
['CCC','MG_0002'] #...


为此,我将它们放入列表列表中

listoflists =[['AAA','MG_00013'],['AAA','MG_00177'],['AAA','MG_00005'],['BBB','MG_0045'],['BBB','MG_00080'],['CCC','MG_0002']]


我从这里迷路了...

for i in listoflists:
if i[0] == i[0]:
    test.append(i[1])

for i in test:
    print(i)


结果为False。

我认为逻辑是将它们分成以下列表,比较字母数字ID并选择最低的ID。

[(AAA,['MG_00013','MG_00177','MG_00005'])]


但是,我现在完全迷失了自己,感到沮丧……

请您帮我解决一下吗?

==============================================
每个人都帮助我,真是太好了!
但是,必须考虑ID的长度。
例如,每个人都给我BBB和MG_00080,但它假设MG_0045因为45小于80 ...

最佳答案

ll =[['AAA','MG_00013'],
    ['AAA','MG_00177'],
    ['AAA','MG_00005'],
    ['BBB','MG_0045'],
    ['BBB','MG_00080'],
    ['CCC','MG_0002']]

d = {}
for l in ll:
    # If key is not the dict, insert the entry into dict
    if l[0] not in d:
        d[l[0]] = l[1]
    # If key is already in the dict, update the entry if value is smaller
    elif int(l[1][3:]) < int(d[l[0]][3:]):
        d[l[0]] = l[1]

print d


输出:

{'AAA': 'MG_00005', 'BBB': 'MG_0045', 'CCC': 'MG_0002'}

关于python - python从多个列表中选择具有引用的最低字母数字值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19750589/

10-16 11:21
查看更多