我想根据主字典中的属性中是否存在任何字符串数组,将字典拆分为两个。目前我可以通过两个单独的字典理解来实现这一点(下面),但是只有一个行/字典理解有更有效的方法吗?
included = {k:v for k,v in users.items() if not any(x.lower() in v["name"].lower() for x in EXCLUDED_USERS)}
excluded = {k:v for k,v in users.items() if any(x.lower() in v["name"].lower() for x in EXCLUDED_USERS)}
修改
EXCLUDED_USERS
包含模式列表。
答案 0 :(得分:3)
这个解决方案更加冗长,但它应该更高效,可能更具可读性:
included = {}
excluded = {}
lower_excluded_users = [x.lower() for x in EXCLUDED_USERS]
for k,v in users.items():
if any(x in v["name"].lower() for x in lower_excluded_users):
excluded[k] = v
else:
included[k] = v
我认为一次理解不能做到这一点。可以在k:v
语句中使用a ternary operator,在else
模式中if
之后无法使用{k:v for k,v in users.items() if k ...}
。
答案 1 :(得分:0)
一行解决方案(lower_excluded_users
我无法抗拒)
included, excluded = dict(), dict()
# ssly, you don't have to do this everytime
lower_excluded_users = [x.lower() for x in EXCLUDED_USERS]
# and now the one-line answer using if-else-for construct with
# v substituted by D[k]. And instead of using `for k, v in dicn.items()`
# I have used [... for aKey in dicn.keys()]
[ excluded.update({aKey: users[aKey]}) \
if any(x in users[aKey]["name"].lower() for x in lower_excluded_users) \
else \
included.update({aKey: users[aKey]}) \
for aKey in users.keys()
]
或者没有美化的人:
[excluded.update({aKey: users[aKey]}) if any(x in users[aKey]["name"].lower() for x in lower_excluded_users) else included.update({aKey: users[aKey]}) for aKey in users.keys()]