Python Codewars:有人可以解释 how/why 发生这种情况吗?
Python Codewars: can someone explain how/why this happens?
我正在做 Codewars,但被这个简单的问题卡住了。问题是:
Your goal in this kata is to implement a difference function, which subtracts one list from
another and returns the result.
It should remove all values from list a, which are present in list b keeping their order.
If a value is present in b, all of its occurrences must be removed from the other.
这是我试过的:
def array_diff(a, b):
if a == []: return b
if b == []: return a
for occurrence in b:
if occurrence in a:
a.remove(occurrence)
return a
由于某种原因我有 2 次失败的测试,这些失败测试的要求是:
a was [1,2,2], b was [2], expected [1]: [1, 2] should equal [1]
a was [], b was [1,2], expected []: [1, 2] should equal []
任何人都可以帮助我并在可能的情况下解释一下吗?任何帮助表示赞赏。
编辑:我的借口是我是 Python 的初学者所以,如果这个问题太明显了,我很抱歉 errors/mistakes
您可以尝试修改您的代码如下:
def array_diff(a, b):
if a == []: return a
if b == []: return a
for occurrence in b:
if occurrence in a:
a = list(filter(lambda val: val != occurrence, a)
return a
我修好了。如果有人遇到同样的问题,这里是代码:
第一个代码是Matthias提供的,比较干净,请使用。
def array_diff(a, b):
return [value for value in a if value not in b]
# CREDITS TO MATTHIAS FOR THIS SIMPLE SOLUTION
我的代码,如果有人感兴趣的话:
def array_diff(a, b):
#if a == []: return b
#if b == []: return a
# these if statements are replaced by the"for item in range" code below
for occurrence in b:
if occurrence in a:
for item in range(a.count(occurrence)):
a.remove(occurrence)
return a
我正在做 Codewars,但被这个简单的问题卡住了。问题是:
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list a, which are present in list b keeping their order. If a value is present in b, all of its occurrences must be removed from the other.
这是我试过的:
def array_diff(a, b):
if a == []: return b
if b == []: return a
for occurrence in b:
if occurrence in a:
a.remove(occurrence)
return a
由于某种原因我有 2 次失败的测试,这些失败测试的要求是:
a was [1,2,2], b was [2], expected [1]: [1, 2] should equal [1]
a was [], b was [1,2], expected []: [1, 2] should equal []
任何人都可以帮助我并在可能的情况下解释一下吗?任何帮助表示赞赏。 编辑:我的借口是我是 Python 的初学者所以,如果这个问题太明显了,我很抱歉 errors/mistakes
您可以尝试修改您的代码如下:
def array_diff(a, b):
if a == []: return a
if b == []: return a
for occurrence in b:
if occurrence in a:
a = list(filter(lambda val: val != occurrence, a)
return a
我修好了。如果有人遇到同样的问题,这里是代码: 第一个代码是Matthias提供的,比较干净,请使用。
def array_diff(a, b):
return [value for value in a if value not in b]
# CREDITS TO MATTHIAS FOR THIS SIMPLE SOLUTION
我的代码,如果有人感兴趣的话:
def array_diff(a, b):
#if a == []: return b
#if b == []: return a
# these if statements are replaced by the"for item in range" code below
for occurrence in b:
if occurrence in a:
for item in range(a.count(occurrence)):
a.remove(occurrence)
return a