【发布时间】:2020-01-13 18:05:13
【问题描述】:
leetcode 27. Remove Element的以下两个答案有什么区别? 他们两个都返回相同的输出,但只接受了 no.1。我不知道为什么 no.2 是不可接受的。
输出
#Output
[2,2]
程序
1号
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
for x in nums[:]:
if x == val:
nums.remove(x)
return nums
2号
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
result = [s for s in nums if s != val]
result = str(result).replace(' ', '')
return result
【问题讨论】:
-
他们不返回相同的东西,第二个返回一个字符串并且它不会改变列表
-
我修好了,但在 leetcode 平台上还是不行。
-
再说一遍,它不会改变列表
-
我已经摆脱了
len()。 -
你明白我在说什么吗?这不是唯一的问题。同样,您的第二个版本永远不会按照问题指定的方式改变原始列表。
标签: python arrays python-3.x list