gpt4 book ai didi

python - 类型错误 : 'int' object is not subscriptable when reversing a number

转载 作者:行者123 更新时间:2023-12-01 09:16:44 30 4
gpt4 key购买 nike

我试图找出一个数字是否是回文数。我的代码是:

max = 10 ** n
length = 0
total = 0
for i in range (max):
if i == i[::-1]:
total += 1
if len(i) == n:
length += 1

if i == i[::-1]: 给出错误 TypeError: 'int' object is not subscriptable。 n是一个整数。

最佳答案

变量 i 是一个整数,但您尝试通过

访问其中的元素,就好像它是列表一样
if i == i[::-1]:

我认为在这种情况下,你想要

if str(i) == str(i)[::-1]:

并且还将 i 转换为 if len(str(i)) == n:

内的字符串

但是,这样做可能更容易:

for i in map(str,range(max)):

关于python - 类型错误 : 'int' object is not subscriptable when reversing a number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181824/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com