猿问

list[-1] 不以列表的最后一项为目标(回文中有两个连续的零)

我正在编写一个简单的代码来检查数字是否为回文。每当数字有两个连续的零时,print('removing',palind[-1])将列表中的错误零作为目标。


n = 200314413002

x = n

palind = []

while n > 0:

    d = n % 10

    n = n // 10

    palind.append(d)

    

print(palind, 'is to check')    

    

actual_palind = []


for i in palind:

    if palind[0] == palind[-1] and len(palind) % 2 == 0:

        print('removing',palind[0])

        palind.remove(palind[0])

        print('removing',palind[-1])

        palind.remove(palind[-1])

        print(palind,'is still a palindrome')

        actual_palind.append(x)

    else:

        print(x,'is not a palindrome')

        break

        

print(x, 'is a palindrome')

这是输出


[2, 0, 0, 3, 1, 4, 4, 1, 3, 0, 0, 2] is to check

removing 2

removing 2

[0, 0, 3, 1, 4, 4, 1, 3, 0, 0] is still a palindrome

removing 0

removing 0

[3, 1, 4, 4, 1, 3, 0, 0] is still a palindrome

200314413002 is not a palindrome

200314413002 is a palindrome

我错过了什么?


拉丁的传说
浏览 100回答 2
2回答

一只甜甜圈

这不会从列表中删除最后一项:palind.remove(palind[-1])它删除列表的第一项 equals palind[-1],如果有多个相等的项目,这将是一个问题。要删除列表的最后一项,请执行以下操作:del palind[-1]

拉莫斯之舞

就像 zvone 在他们的回答中所说的那样,它remove()不会根据索引删除,而是根据值删除。要根据索引删除,请使用.pop():for i in palind:    if palind[0] == palind[-1] and len(palind) % 2 == 0:        print('removing',palind.pop(0))        print('removing',palind.pop(-1))        print(palind,'is still a palindrome')        actual_palind.append(x)    else:        print(x,'is not a palindrome')        break        输出:[2, 0, 0, 3, 1, 4, 4, 1, 3, 0, 0, 2] is to checkremoving 2removing 2[0, 0, 3, 1, 4, 4, 1, 3, 0, 0] is still a palindromeremoving 0removing 0[0, 3, 1, 4, 4, 1, 3, 0] is still a palindromeremoving 0removing 0[3, 1, 4, 4, 1, 3] is still a palindromeremoving 3removing 3[1, 4, 4, 1] is still a palindrome200314413002 is a palindrome
随时随地看视频慕课网APP

相关分类

Python
我要回答