记录索引

2024-10-01 17:26:57 发布

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

我想获得列表f中SeqRecords的索引列表。我试过这个:

for x in f:
    ind = f.index(x)
    print(ind)

但我得到了一个错误:

0
Traceback (most recent call last):

File "C:\Users\Adrian\Desktop\Sekwencje\skrypt 1.py", line 43, in <module>
  ind = f.index(x)

File "C:\Users\Adrian\anaconda3\lib\site-packages\Bio\SeqRecord.py", line 803, in __eq__
  raise NotImplementedError(_NO_SEQRECORD_COMPARISON)

NotImplementedError: SeqRecord comparison is deliberately not implemented. Explicitly compare the 
attributes of interest.

谢谢你的回答


Tags: inpy列表forindex错误lineseqrecord
1条回答
网友
1楼 · 发布于 2024-10-01 17:26:57

解释

您无法在列表中获取和SeqRecord的索引,因为“SeqRecord比较故意未实现”(您在错误消息-NotImplementedError中得到了解释)。index()方法返回obj出现的列表中的最低索引。但要做到这一点,它需要一种特定的比较方法,这种方法没有在Seq模块中实现

硬法

因为python是一种动态语言,所以可以向类添加一个比较方法。甚至错误消息也会给出答案(显式比较 感兴趣的属性)。下面是一个代码:

from Bio.SeqRecord import SeqRecord

def equal_seqs(self, other):
    if not isinstance(other, SeqRecord):
        raise NotImplementedError('Comparsion on wrong types!')
    else:
        return self.seq == other.seq # You can change it to whatever you want.

SeqRecord.__eq__ = equal_seqs

foo = SeqRecord('ATGCGCAT')
bar = SeqRecord('GACGATCA')

print(foo == bar)
# False

l = [foo, bar]
print(l.index(bar))
# 1

其他可能性

我不知道我是否理解正确,但如果您想打印序列的ID,则可以按以下方式执行:

for seq in sequences:
    print(f'{seq.id} {seq.name}')

这就是你想要的吗

更多信息

如果您想阅读有关富比较方法的更多信息,那么您可以找到它here

相关问题 更多 >

    热门问题