Leetcode练习<九> 删除列表中的元素

# @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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值