【发布时间】:2022-11-16 21:21:25
【问题描述】:
我有如下 JSON
dict =[
{'name':'Test01'
},
{'name':'Tests04'
}
]
我想删除不符合name规则的字典
规则:4位单词2 位数数字
这里Tests04不跟4位数字单词2 位数数字规则,它包含 5 位数字的单词。
【问题讨论】:
-
不要使用内置函数名称作为变量,尤其是当您使用 dict 来表示列表时!
标签: python json dictionary
我有如下 JSON
dict =[
{'name':'Test01'
},
{'name':'Tests04'
}
]
我想删除不符合name规则的字典
规则:4位单词2 位数数字
这里Tests04不跟4位数字单词2 位数数字规则,它包含 5 位数字的单词。
【问题讨论】:
标签: python json dictionary
编写一个根据您的规则验证值的函数。用列表理解重建原始列表。
from string import ascii_letters, digits
def isvalid(s):
return len(s) == 6 and all(c in ascii_letters for c in s[:4]) and all(c in digits for c in s[4:])
_list = [
{'name': 'Test01'},
{'name': 'Tests04'}
]
_list = [e for e in _list if isvalid(e['name'])]
print(_list)
输出:
[{'name': 'Test01'}]
【讨论】:
您还可以使用正则表达式来解析值:
import re
mylist = [
{'name': 'Test01' },
{'name': 'Tests04' }
]
regex = re.compile(r'^w{4}d{2}$')
mylist = [{k:v} for _ in mylist for k,v in _.items() if regex.match(v)]
# Or, maybe this is more clear?
# mylist = [item for item in mylist if regex.match(list(item.values())[0])]
print(mylist)
这将返回:
[{'name': 'Test01'}]
这表示要查找四个“单词”字符,然后查找每个对象值的开头和结尾之间的两位数字。任何与此模式不匹配的内容都会被过滤掉。查看 w 的定义,确保您和 re 的作者就字符是什么达成一致。
而且,正如@cobra 指出的那样,使用dict 作为变量名(尤其是列表)并不是最佳做法。
【讨论】: