# @greg 20170521 # Given an array and a value, remove all instances of that value in place and return the new length. # Do not allocate extra space for another array, you must do this in place with constant memory. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. # Example: # Given input array nums = [3,2,2,3], val = 3 # Your function should return length = 2, with the first two elements of nums being 2. # 输入一个列表和一个整数, 删除列表中的整数, 返回列表的长度 # 注意:在这个运算过程中,不能创建新的数组,只能在输入数组上操作 class Solution(object): def removeElement(self, nums, val): count = 0 for num in nums: if num == val: count += 1 for i in range(count): nums.remove(val) return len(nums) # 大神的写法 def removeElement1(self, nums, val): try: while True: nums.remove(val) except: return len(nums) # 我的一种错误写法 # 以a = [3, 2, 3, 2] val = 3为例 当nums去掉第一个3后,nums变为[2, 3, 2],而此时for num in nums, 便利取到的 # 数字却是num = 3, 不是2.所以我这种写法有问题 def removeElement2(self, nums, val): for num in nums: if num == val: nums.remove(val) return len(nums) if __name__ == '__main__': nums = [3, 2, 3, 3, 2] val = 3 s = Solution() print(s.removeElement1(nums, val))
删除列表元素的集中方法:
1根据下标来删除元素
a = [3, 2, 2, 3]
del a[2]
删除下标为2的元素
2使用pop来删除最后一个元素
a = [3, 2, 3, 2]
a.pop()
删除最后一个元素
3remove 删除指定值的元素(一次只删除一个元素)
a = [3, 2, 2, 3]
a.remove(3)
删除第一个3