获取具有组合索引的列表中的值
getting the value on a list with a combined index
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”对象不可订阅。
我该如何解决这个问题?
您必须先将数字转换为字符串:
>>> 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]
。
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”对象不可订阅。
我该如何解决这个问题?
您必须先将数字转换为字符串:
>>> 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]
。