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))
已由其他人为我完成,我大致知道它将车牌放入新的如果与英国车牌结构的模式
不匹配,请列出。这是老师布置的任务,所以我也需要一一解释代码的不同部分。
我的问题是:
filter
和 lambda
在 foreign_numbers = list(filter(lambda x: re.match(pattern, x), number_plates))
中做什么外国车牌被放入新列表中是因为它们与模式不匹配?
最佳答案
您的问题分为两个部分。
lambda
只是编写函数的不同方式:def find_non_uk(x): return re.match(pattern, x)
与:
相同find_non_uk = lambda x: re.match(pattern, x)
lambda
你能做的事情相当有限。它本质上仅限于一行,并且全部必须是一个表达式。使用def
,就没有这样的限制。您可以在函数体中使用多行和语句。filter
将给定函数应用于列表中的每个元素,并仅返回列表中返回值为 true 的元素。来自文档字符串: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()
将迭代器转换为列表。
如果这看起来太复杂并且您知道列表推导式,请使用它们:
pattern = re.compile("(?![A-Z]{2}\d{2}\s+[A-Z]{3}$)")
foreign_numbers = [x for x in number_plates if pattern.match(x)]
关于python - 如何用一行代码解释filter和lambda的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33937023/