首页 > 解决方案 > 使用组合索引获取列表中的值

问题描述

coded = ['','','','','','','','','','',
        'a','b','c','d','e','f','g','h','i',
        'j','k','l','m','n','o','p','q','r',
        's','t','u','v','w','x','y','z',' ']

def decode(decode):
     out = ''
     for x in range(1, len(str(decode)) // 2):
          out += coded[int(str(decode[x * 2 - 2]) + str(decode[x * 2 - 1]))]  #here is the issue
     return out

print(decode(16133335202320))

我试图从输入值中每 2 个字符从列表中获取一个值。但是,在我评论的地方,它不断提出“int' object is not subscriptable”。

我该如何解决?

标签: pythonlistinteger

解决方案


您必须先将您的号码转换为字符串:

>>> print(decode(16133335202320))
...
TypeError: 'int' object is not subscriptable


#         HERE ---v
>>> print(decode(str(16133335202320)))
gdxzkn

或者

你可以重写你的函数,如下所示:

def decode(decode):
     decode = str(decode)
     out = ''
     for x in range(1, len(decode) // 2):
          out += coded[int(decode[x * 2 - 2] + decode[x * 2 - 1])]
     return out
>>> print(decode(16133335202320))
gdxzkn

推荐阅读