如何在Robot Framework/Python中用正则表达式过滤字典列表?
使用正则表达式过滤字典列表
我有如下字典列表,希望用正则表达式J.*过滤,只保留firstname以J开头的条目:
people_list = [ {'age': 20,'firstname':'John', 'lastname': 'Smith'}, {'age': 25,'firstname':'Joy', 'lastname': 'Jones'}, {'age': 30,'firstname':'Bill', 'lastname': 'Lee'} ]
期望得到的结果:
matches = [ {'age': 20,'firstname':'John', 'lastname': 'Smith'}, {'age': 25,'firstname':'Joy', 'lastname': 'Jones'} ]
以下是Python和Robot Framework的实现方案:
Python 实现
列表推导式 + re.match
直接通过列表推导式遍历列表,用正则匹配firstname字段:
import re people_list = [ {'age': 20,'firstname':'John', 'lastname': 'Smith'}, {'age': 25,'firstname':'Joy', 'lastname': 'Jones'}, {'age': 30,'firstname':'Bill', 'lastname': 'Lee'} ] # 筛选firstname以J开头的字典 matches = [person for person in people_list if re.match(r'J.*', person['firstname'])] print(matches)
re.match会从字符串起始位置匹配,刚好满足J.*的需求——匹配以J开头的任意长度字符串。
预编译正则(复用场景推荐)
如果需要多次使用该正则规则,预编译可以提升执行效率:
import re # 预编译正则表达式 pattern = re.compile(r'J.*') matches = [person for person in people_list if pattern.match(person['firstname'])]
Robot Framework 实现
方法1:嵌入Python代码块
直接在Robot脚本中使用Python列表推导式结合re库:
*** Settings *** Library Collections Library re *** Test Cases *** Filter Dictionary List # 构造目标列表 ${people_list} Create List ... ${age=20, firstname=John, lastname=Smith} ... ${age=25, firstname=Joy, lastname=Jones} ... ${age=30, firstname=Bill, lastname=Lee} # 执行过滤 ${matches} Evaluate [p for p in $people_list if re.match(r'J.*', p['firstname'])] re # 输出结果 Log ${matches}
方法2:循环遍历筛选
如果偏好纯Robot关键字实现,可以通过循环逐个判断:
*** Settings *** Library Collections Library re *** Test Cases *** Filter List With Loop ${people_list} Create List ... ${age=20, firstname=John, lastname=Smith} ... ${age=25, firstname=Joy, lastname=Jones} ... ${age=30, firstname=Bill, lastname=Lee} ${matches} Create List :FOR ${person} IN @{people_list} \ ${firstname} Get From Dictionary ${person} firstname \ ${is_match} Evaluate re.match(r'J.*', '${firstname}') re \ Run Keyword If ${is_match} Append To List ${matches} ${person} Log ${matches}
内容的提问来源于stack exchange,提问作者lengineer
相关产品推荐
相关产品推荐

