【问题标题】:Error in sorting operation on dictionary字典排序操作出错
【发布时间】:2015-06-09 12:57:48
【问题描述】:

我正在尝试根据某个参数对序列文件进行排序。数据如下:

ID1 ID2 32

MVKVYAPASSANMSVGFDVLGAAVTP ...

ID1 ID2 18

MKLYNLKDHNEQVSFAQAVTQGLGKN ...

....

这样的序列大约有 3000 个,即第一行包含两个 ID 字段和一个排名字段(排序键),而第二行包含序列。我的方法是打开文件,将文件对象转换为列表对象,将注释行(ID1、ID2、等级)与实际序列分开(注释行总是出现在偶数索引上,而序列行总是出现在奇数索引上) ,将它们合并到字典中,并使用排名字段对字典进行排序。代码如下:

#!/usr/bin/python

with open("unsorted.out","rb") as f:
    f = f.readlines()

assert type(f) == list, "ERROR: file object not converted to list"

annot=[]
seq=[]

for i in range(len(f)):
    # IDs
    if i%2 == 0:
        annot.append(f[i])
    # Sequences     
    elif i%2 != 0:
        seq.append(f[i])

# Make dictionary
ids_seqs = {}         
ids_seqs = dict(zip(annot,seq))

# Solub rankings are the third field of the annot list, i.e. annot[i].split()[2]
# Use this index notation to rank sequences according to solubility measurements 

sorted_niwa = sorted(ids_seqs.items(), key = lambda val: val[0].split()[2], reverse=False)

# Save to file
with open("sorted.out","wb") as out:
    out.write("".join("%s %s" % i for i in sorted_niwa))

我遇到的问题是,当我打开已排序的文件进行手动检查时,当我向下滚动时,我注意到某些序列已被错误排序。例如,我看到第 9 位排在第 89 位之后。直到某一点,排序是正确的,但我不明白为什么它一直没有工作。

非常感谢您的帮助!

【问题讨论】:

  • 您正在对字符串进行排序。 “89”
  • @Karoly:是的,我刚刚注意到凯文指出的。感谢您的快速回复!

标签: python sorting dictionary


【解决方案1】:

听起来您是在比较字符串而不是数字。 "9" > "89" 因为字符 '9' 按字典顺序出现在字符 '8' 之后。尝试在您的密钥中转换为整数。

sorted_niwa = sorted(ids_seqs.items(), key = lambda val: int(val[0].split()[2]), reverse=False)

【讨论】:

  • 闪电般的快!谢谢,我不会撒谎,那是个愚蠢的错误!
猜你喜欢
  • 1970-01-01
  • 2020-09-21
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 2011-05-06
相关资源
最近更新 更多