亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從有條件的字典列表中提取字典

如何從有條件的字典列表中提取字典

PHP
叮當貓咪 2023-11-09 21:16:03
如何從帶有條件的json中提取我有一個字典列表。我需要在某些條件下提取一些字典如果對于跨字段我需要“AND”條件對于相同的字段數組,我需要 OR 條件我需要搜索subject哪個是Physics或Accounting這是字段數組(OR)語句和我需要搜索type是Permanent或GUEST條件這是字段數組(OR)語句和我需要搜索Locationis NY(&) 條件test = [{'id':1,'name': 'A','subject': ['Maths','Accounting'],'type':'Contract', 'Location':'NY'},      { 'id':2,'name': 'AB','subject': ['Physics','Engineering'],'type':'Permanent','Location':'NY'},    {'id':3,'name': 'ABC','subject': ['Maths','Engineering'],'type':'Permanent','Location':'NY'},{'id':4,'name':'ABCD','subject': ['Physics','Engineering'],'type':['Contract','Guest'],'Location':'NY'}]預期輸出是 id[{ 'id':2,'name': 'AB','subject': ['Physics','Engineering'],'type':'Permanent','Location':'NY'},{'id':4,'name':'ABCD','subject': ['Physics','Engineering'],'type':['Contract','Guest'],'Location':'NY'}]
查看完整描述

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'}]


查看完整回答
反對 回復 2023-11-09
?
翻閱古今

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)


查看完整回答
反對 回復 2023-11-09
  • 2 回答
  • 0 關注
  • 172 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號