作者mikapauli (桜花)
看板Python
標題Re: [問題] 刪除list中特定的element
時間Mon Feb 3 10:38:48 2014
※ 引述《neurone (明月照大江)》之銘言:
: 小弟有個問題請各位大師,我想要刪掉input list中特定的element
: 以下為例,想要刪掉值為0,9 的element。但是index=7的0 刪不掉。
: 請問程式碼哪裡出錯造成這樣的問題?
: 謝謝各位撥冗解救小弟
: ================================
: input = [0,0,1,2,3,4,0,5,6,7,8]
: del_char = [0,9]
: print input
: for item in input:
: if item in del_char:
: input.remove(item)
: print input
: ================================
: 預期結果:[1,2,3,4,5,6,7,8]
: 實際結果:[1,2,3,4,0,5,6,7,8]
remove(...)
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
簡單舉例來說:
>>> input = [0, 0, 1, 2, 3, 4, 0, 5, 6, 7, 8]
>>> input.remove(input[6])
>>> print(input)
[0, 1, 2, 3, 4, 0, 5, 6, 7, 8]
另外順便練習一下用map和filter的寫法
list(map(int,
filter(None,
map(str.__mul__,
map(str,
input),
map(False.__eq__,
map(del_char.__contains__,
input))))))
--
「……私も、…っ、
母様の娘に生まれて…
母様とこれまでともに過ごしてきて…
本当に、
幸せでございました…っ!!」
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.242.205.50
推 tiefblau:我想知道第二種寫法有什麼好處?? 02/03 10:50
→ mikapauli:不用想變數名稱XD 02/03 12:03
推 flarehunter:看起來是寫lisp成癮的人XDD 02/03 15:49