2 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
這不會(huì)從列表中刪除最后一項(xiàng):
palind.remove(palind[-1])
它刪除列表的第一項(xiàng) equals palind[-1]
,如果有多個(gè)相等的項(xiàng)目,這將是一個(gè)問題。
要?jiǎng)h除列表的最后一項(xiàng),請執(zhí)行以下操作:
del palind[-1]

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
就像 zvone 在他們的回答中所說的那樣,它remove()不會(huì)根據(jù)索引刪除,而是根據(jù)值刪除。要根據(jù)索引刪除,請使用.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 check
removing 2
removing 2
[0, 0, 3, 1, 4, 4, 1, 3, 0, 0] is still a palindrome
removing 0
removing 0
[0, 3, 1, 4, 4, 1, 3, 0] is still a palindrome
removing 0
removing 0
[3, 1, 4, 4, 1, 3] is still a palindrome
removing 3
removing 3
[1, 4, 4, 1] is still a palindrome
200314413002 is a palindrome
添加回答
舉報(bào)