如何在一行代码中解释filter和lambda的功能?

2024-09-28 22:43:32 发布

您现在位置:Python中文网/ 问答频道 /正文

number_plates = ["DV61 GGB",      #UK
                 "D31 EG 2A",     #F
                 "5314 10A02",    #F
                 "24TEG 5063",    #F
                 "TR09 TRE",      #UK
                 "524 WAL 75",    #F
                 "TR44 VCZ",      #UK
                 "FR52 SWD",      #UK
                 "100 GBS 12",    #F
                 "HG55 BPO"       #UK
                 ]

# Find the non-UK plates
pattern = "(?![A-Z]{2}\d{2}\s+[A-Z]{3}$)"
foreign_numbers = list(filter(lambda x: re.match(pattern, x), number_plates))

这是我代码的一部分。这个foreign_numbers = list(filter(lambda x: re.match(pattern, x), number_plates))是别人帮我做的,我大致知道,如果它与英国车牌结构的pattern不匹配,它会把车牌放入一个新的列表中。这是我老师布置的一个任务,所以我还需要逐一解释代码的不同部分。在

我的问题是: 在filter和{}中,foreign_numbers = list(filter(lambda x: re.match(pattern, x), number_plates))如何将外来板块放入新列表中,因为它们与模式不匹配?在


Tags: lambda代码renumber列表matchfilterlist
3条回答

list(filter(lambda x: re.match(pattern, x), number_plates))中,filter函数本身返回通过检查的元素列表(在本例中匹配regex模式)-就像我们用来过滤液体以制作果子露一样。而列表函数将其转换为列表。所以

foreign_numbers = list(filter(lambda x: re.match(pattern, x), number_plates))是将匹配的数字分隔成一个名为foreign_numbers的列表的代码

>>>print foreign_numbers
>>>['D31 EG 2A', '5314 10A02', '24TEG 5063', '524 WAL 75', '100 GBS 12']

lambda的函数是从number_plates列表中逐个获取元素并传递给re.match。在

如果将模式编译为RegexObject,则不必创建lambda,因为只需使用对象的^{}方法:

pattern = re.compile("(?![A-Z]{2}\d{2}\s+[A-Z]{3}$)")
foreign_numbers = list(filter(pattern.match, number_plates))

为每个车牌号调用match方法,如果匹配,filter将保留它。在

你的问题有两个部分。在

  1. lambda只是编写函数的另一种方法:

    def find_non_uk(x):
        return re.match(pattern, x)
    

    同:

    ^{pr2}$

    lambda在你能做的事情上是相当有限的。它基本上只限于一行,所有的都必须是一个表达式。使用def,没有这样的限制。可以在函数体中使用多行和多个语句。

  2. filter将给定函数应用于列表的每个元素,并只返回返回返回值为true的列表元素。从docstring:

    filter(function or None, iterable) > filter object

    Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

你可以这样写你的台词:

foreign_numbers = list(filter(find_non_uk, number_plates))

您需要外部的list()将迭代器转换为列表。在

如果这看起来太复杂了,而且你知道列表的含义,请使用它们:

^{4}$

相关问题 更多 >