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))
如何将外来板块放入新列表中,因为它们与模式不匹配?在
在
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
的列表的代码lambda
的函数是从number_plates
列表中逐个获取元素并传递给re.match
。在如果将模式编译为RegexObject,则不必创建lambda,因为只需使用对象的^{} 方法:
为每个车牌号调用
match
方法,如果匹配,filter
将保留它。在你的问题有两个部分。在
lambda
只是编写函数的另一种方法:同:
^{pr2}$lambda
在你能做的事情上是相当有限的。它基本上只限于一行,所有的都必须是一个表达式。使用def
,没有这样的限制。可以在函数体中使用多行和多个语句。filter
将给定函数应用于列表的每个元素,并只返回返回返回值为true的列表元素。从docstring:你可以这样写你的台词:
您需要外部的
list()
将迭代器转换为列表。在如果这看起来太复杂了,而且你知道列表的含义,请使用它们:
^{4}$相关问题 更多 >
编程相关推荐