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 關注
- 172 瀏覽
添加回答
舉報