2 回答

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
這里的問(wèn)題主要是你的數(shù)據(jù)不統(tǒng)一,有時(shí)是字符串,有時(shí)是列表。咱們?cè)囋嚢桑?/p>
# 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貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
以下帶有嵌套 if 子句的簡(jiǎn)單方法解決了該問(wèn)題。條件and是通過(guò)嵌套完成的if,or條件只是通過(guò) 完成or。
該in運(yùn)算符適用于字符串值和列表值,因此它可以互換使用并產(chǎn)生預(yù)期的結(jié)果。但這種方法期望沒(méi)有像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 關(guān)注
- 188 瀏覽
添加回答
舉報(bào)