嘿,我对python还很陌生,我自学了它,最终在我的编码技能上有所进步。我已经想到了使用map/filter/reduce函数。我正在尝试朋友给我的一个挑战,使用remove filter和reduce从列表中删除和元素
这是我过滤的代码
def removeall_ft(item, test_list):
res = list(filter(lambda x: x!=item, test_list))
return res
print(removeall_ft(0, [1,0,1]))
it gives [1,1]
工作良好的
导入函数工具
def removeall_rd(item, test_list):
res = functools.reduce(lambda x,y: x if y!=item else x, test_list)
return res
print(removeall_ft(0, [1,0,1]))
但这并没有给我想要的答案。对此表示感谢
functools.reduce返回一个新的(或突变的(对象
def reduce_step(return_so_far,this_value):
if this_value !=item:
return [*return_so_far,this_value]
return return_so_far
它需要一种减少的方法、一个目标列表和一个可选的结果初始值(return_so_far
(
item = 4
result = reduce(reduce_step,[1,2,3,4,5,6,7],[])
print(result)
正如评论中所提到的,这不是一个过滤列表的好方法