2 回答
TA贡献1963条经验 获得超6个赞
这里的问题主要是你的数据不统一,有时是字符串,有时是列表。咱们试试吧:
# turns the values into set for easy comparison
def get_set(d,field):
return {d[field]} if isinstance(d[field], str) else set(d[field])
# we use this to filter
def validate(d):
# the three lines below corresponds to the three conditions listed
return get_set(d,'subject').intersection({'Physics','Accounting'}) and \
get_set(d,'type').intersection({'Permanent', 'Guest'}) and \
get_set(d,'Location')=={'NY'}
result = [d for d in test if validate(d)]
输出:
[{'id': 2,
'name': 'AB',
'subject': ['Physics', 'Engineering'],
'type': 'Permanent',
'Location': 'NY'},
{'id': 4,
'name': 'ABCD',
'subject': ['Physics', 'Engineering'],
'type': ['Contract', 'Guest'],
'Location': 'NY'}]
TA贡献1780条经验 获得超5个赞
以下带有嵌套 if 子句的简单方法解决了该问题。条件and是通过嵌套完成的if,or条件只是通过 完成or。
该in运算符适用于字符串值和列表值,因此它可以互换使用并产生预期的结果。但这种方法期望没有像XYZ Accounting.
result = []
for elem in test:
# Check Location
if elem['Location'] == 'NY':
# Check subject
subject = elem['subject']
if ('Accounting' in subject) or ('Physics' in subject):
# Check type
elem_type = elem['type']
if ('Permanent' in elem_type) or ('Guest' in elem_type):
# Add element to result, because all conditions are true
result.append(elem)
- 2 回答
- 0 关注
- 107 浏览
添加回答
举报