Lambda函数同时包含if和for循环

huangapple go评论54阅读模式
英文:

Lambda function with both if and for loop

问题

data = ['AUD.TR.....1,000.00\n', ' 10   200    HEADING\n', ' ']
regex = {
    'key': '^([A-Z]){3}\.[A-Z]{2}\.*.*\\n$',
    'head': '^\s*[0-9]*\s*[0-9]*\s*[A-Z]*\\n$'
}

test_regex = lambda string: next((j for j in regex if re.match(regex[j], string)), None)

print(list(map(test_regex, data)))
英文:

I am learning lambda funciton. Is there any way to rewrite the test_regex function with lambda in one line?

data=['AUD.TR.....1,000.00\n', '  10   200    HEADING\n', '  ']
regex={
    'key': '^([A-Z]){3}\.[A-Z]{2}\.*.*\\n$',
    'head': '^\s*[0-9]*\s*[0-9]*\s*[A-Z]*\\n$'  
      }

def test_regex(string):
    for j in regex:
        if re.match(regex[j], string):
            return j
    else:
        return None

print(list(map(test_regex, data)))

答案1

得分: 1

def test_regex(string):
return next((j for j in regex if re.match(regex[j], string)), None)

next 返回 re.match(regex[j], string) 成功的第一个 j 的值。如果生成器从未产生值,next 返回 None

英文:

You can write this in one line, but you don't need a lambda expression to do so.

def test_regex(string):
    return next((j for j in regex if re.match(regex[j], string)), None)

next returns the first value of j for which re.match(regex[j], string) succeeds. next returns None if the generator never produces a value.

答案2

得分: 0

这一行代码将有效:

test_regex = lambda string: next((j for j in regex if re.match(regex[j], string)), None)
英文:

This line will work:

test_regex = lambda string: next((j for j in regex if re.match(regex[j], string)), None)

(You could, however, write the function itself in a single line, but that is not the same and not what you asked for.)

huangapple
  • 本文由 发表于 2023年3月9日 23:34:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定