【问题标题】:What is the difference between [:] and [] in python? [duplicate]python中的[:]和[]有什么区别? [复制]
【发布时间】:2018-02-01 18:06:40
【问题描述】:

我在 leetcode(27) 中提交答案。我需要取回正确的列表和长度。当我打算这样做时。

输入: [3,2,2,3] 3

class Solution:
    def removeElement(self, nums, val):
        if not nums:
            return 0
        nums = [i for i in nums if val != i]
        return len(nums)

Output:       [3,2]
Expected:     [2,2]

显然我的回答是错误的。但是当我这样写时,解决方案是正确的。

class Solution:
    def removeElement(self, nums, val):
        if not nums:
            return 0
        nums[:] = [i for i in nums if val != i]
        return len(nums)

Output:       [2,2]
Expected:     [2,2]

我不明白这两种方式之间的区别。为什么我会得到两个不同的列表?

【问题讨论】:

    标签: python


    【解决方案1】:

    nums[:] 原地改变原来的 nums。

    https://docs.python.org/3/tutorial/introduction.html#lists

    【讨论】:

    • 投反对票时,请大声说出一些理由...
    猜你喜欢
    • 2015-05-18
    • 2010-12-10
    • 2016-08-24
    • 2016-02-16
    • 2021-08-11
    • 1970-01-01
    • 2014-02-24
    • 2013-07-14
    • 2021-07-14
    相关资源
    最近更新 更多