简体   繁体   English

如何使用 function 在 Python 中过滤?

[英]How do you filter in Python using a function?

I am using the filter function for the first time and using a function to remove del_num from a tuple called num_list.我第一次使用过滤器 function 并使用 function 从名为 num_list 的元组中删除 del_num。 However, it's not doing what I want.但是,它没有做我想要的。 I am getting back the original num_list values.我正在取回原始的 num_list 值。 Appreciate any ideas on how to get this to work.欣赏有关如何使其发挥作用的任何想法。

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list, del_num):
    new_num =[]
    for v in num_list:
        if (num_list) == (del_num):
            return FALSE
        else:
            new_num.append(v)
    return new_num

result = filter_list(num_list,del_num)
print(result)

One way to do this is using list comprehension一种方法是使用列表理解

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list,del_num):
    return [num for num in num_list if num != del_num]

filtered_list = filter_list(num_list,del_num)
print(filtered_list)

Making minimal changes to the overall structure of your code, but making some changes so it works:对代码的整体结构进行最小的更改,但进行一些更改以使其正常工作:

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list, del_num):
    new_num = []
    for v in num_list:
        if v != del_num:
            new_num.append(v)
    return new_num

result = filter_list(num_list,del_num)
print(result)

The return False portion of your code will break out of the function and return False if the condition is met, which is not what you want.代码的return False部分将脱离 function 并在满足条件时返回False ,这不是你想要的。 Additionally, the equality check you were doing was comparing the original list to the number to be deleted.此外,您所做的相等性检查是将原始列表与要删除的数字进行比较。 You should have done if v == del_num . if v == del_num你应该这样做。 Given that all the action happens in the else block, easiest to turn the equality into an inequality and get rid of the else block entirely.鉴于所有动作都发生在else块中,最容易将等式变为不等式并完全摆脱else块。

Also note that the boolean False is spelt False , not FALSE (unlike some other languages).另请注意, boolean False 拼写为False ,而不是FALSE (与其他一些语言不同)。

Here is what are you looking for:这是您要查找的内容:

num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24

def filter_list(num_list, del_num): def filter_list(num_list, del_num):

 new_num =[]

for v in num_list:
    if (v) == (del_num):
        pass
    else:
        new_num.append(v)
return new_num

result = filter_list(num_list,del_num)结果 = filter_list(num_list,del_num)

print(result)打印(结果)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM