題目來源:
題目分析:
解決代碼:
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
j=0
for i in range(len(nums)):
if(nums[i]!=val):
nums[j]=nums[i]
j+=1
return (j)
關於刪除某個元素的一些方法與差異
1.remove方法:
2.pop方法:
3.del函數:
舉例說明:
>>> str=[1,2,3,4,5,2,6]
>>> del str[1]
>>> str
[1, 3, 4, 5, 2, 6]
>>> str2=['abc','bcd','dce']
>>> del str2[1]
>>> str2
['abc', 'dce']
除此之外,del還可以刪除指定範圍內的值。
>>> str=[0,1,2,3,4,5,6]
>>> del str[2:4] #刪除從第2個元素開始,到第4個爲止的元素(但是不包括尾部元素)
>>> str
[0, 1, 4, 5, 6]
del 也可以刪除整個數據對象(列表、集合等)
>>> str=[0,1,2,3,4,5,6]
>>> del str
>>> str #刪除後,找不到對象
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
str
NameError: name 'str' is not defined
注意:del是刪除引用(變量)而不是刪除對象(數據),對象由自動垃圾回收機制(GC)刪除。