亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

list[-1] 不以列表的最后一項為目標(回文中有兩個連續的零)

list[-1] 不以列表的最后一項為目標(回文中有兩個連續的零)

拉丁的傳說 2023-03-01 16:03:15
我正在編寫一個簡單的代碼來檢查數字是否為回文。每當數字有兩個連續的零時,print('removing',palind[-1])將列表中的錯誤零作為目標。n = 200314413002x = npalind = []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 checkremoving 2removing 2[0, 0, 3, 1, 4, 4, 1, 3, 0, 0] is still a palindromeremoving 0removing 0[3, 1, 4, 4, 1, 3, 0, 0] is still a palindrome200314413002 is not a palindrome200314413002 is a palindrome我錯過了什么?
查看完整描述

2 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

這不會從列表中刪除最后一項:

palind.remove(palind[-1])

它刪除列表的第一項 equals palind[-1],如果有多個相等的項目,這將是一個問題。

要刪除列表的最后一項,請執行以下操作:

del palind[-1]


查看完整回答
反對 回復 2023-03-01
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

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


查看完整回答
反對 回復 2023-03-01
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號