gpt4 book ai didi

python - 怎么用一行代码解释filter和lambda的作用呢?

转载 作者:行者123 更新时间:2023-11-28 21:49:08 25 4
gpt4 key购买 nike

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 则列出。这是我老师布置的任务,所以我也需要对代码的不同部分逐一解释。

我的问题是:filterlambdaforeign_numbers = list(filter(lambda x: re.match(pattern, x), number_plates)) 中做了什么外国车牌因为与模式不匹配而被放置在新列表中?

最佳答案

您的问题分为两部分。

  1. lambda 只是编写函数的一种不同方式:

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

    与 :

    相同
    find_non_uk = lambda x: re.match(pattern, x)

    lambda 的功能相当有限。它本质上仅限于一行,并且所有内容都必须是一个表达式。使用 def 就没有这样的限制。您可以在函数体中使用多行和语句。

  2. 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com