获取具有组合索引的列表上的值


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&;

如何解决这个问题?

您必须将您的号码转换为字符串,然后:

>>> 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

这个答案是基于fischmalte的评论:

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])] ### EDITED LINE
return out
print(decode(16133335202320))

str(decode[x * 2 - 2])改为str(decode)[x * 2 - 2],str(decode[x * 2 - 1])改为str(decode)[x * 2 - 1]

最新更新