【问题标题】:subscriptable error when trying to make a dictionary in to a list尝试将字典放入列表时出现可下标错误
【发布时间】:2014-05-04 17:38:26
【问题描述】:

在我正在处理的代码中,当我尝试将字典放入列表并将该列表拆分为三个字母 rna 密码子时,我收到了一条错误消息。这是我输入的:

for i in range (0, len(self.codon_dict), 3): #in range from the first object to the last         object of the string, in multiples of three
            codon = (list(self.codon_dict.items[i:i+3])) #codons in string are read from      the first object (i) to another object three bases down the string 
            print (codon)
            if codon in NucParams.codon_dict():
                self.codon_dict[codon] +=1

我收到的错误是这样的:

 codon = (list(self.codon_dict.items[i:i+3])) #codons in string are read from the first object (i) to another object three bases down the string
TypeError: 'builtin_function_or_method' object is not subscriptable

当他们说一个对象不可下标时,他们是什么意思?另外,我该如何解决这个错误?谢谢。

注意:NucParams 是我的类,而 codon_dict 是列出发生在氨基酸编码中的三个字母密码子的字典。

【问题讨论】:

  • 如果你使用的是 Python 2,那么它应该是 codon_dict.items()[i:i+3],否则使用 itertools.islice。
  • 我实际上使用的是 python 3。我以前从未使用过 itertools。你能解释一下为什么我必须使用它吗?

标签: python


【解决方案1】:

首先,您尝试为方法(或函数)项下标,而不是函数的结果;你在self.codon_dict.items之后缺少括号()。

其次,假设您像我一样习惯了 Python 2,您可能会惊讶 dict.items() 现在返回字典项目的“视图”;更多信息请参见this SO question。

这里有一些简单的示例代码,展示了如何在 Python 3 中使用 dict.items()。

import itertools

d={'foo':'bar',
   'baz':'quuz',
   'fluml':'sqoob'}

print(list(d.items())[0:2])
print(list(itertools.islice(d.items(),0,2)))

运行它会给出

[('foo', 'bar'), ('baz', 'quuz')]
[('foo', 'bar'), ('baz', 'quuz')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2013-01-21
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多