英文:
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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论