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

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

用于過濾嵌套 python 列表數據的列表理解

用于過濾嵌套 python 列表數據的列表理解

慕桂英4014372 2023-09-05 17:15:36
你好!問題:我想知道如何使用列表理解來根據 python 列表中的單詞過濾掉某些結果,或者以其他方式從列表中僅提取我需要的包含某個“關鍵字”的行。概述:我正在使用 python 向 api 發出請求并收到了 json 請求。我已經使用 json.loads() 轉換了 json,現在有一個我正在嘗試使用的嵌套 python 列表:{"results": [        {            **"id": 12345678,**            "applicant": {                "id": 11342542,                "first_name": "Mary",                "last_name": "Johnson",                "email": "[email protected]"            },            "average_score": 42.0,            "collaborators": [],            "created_at": "2020-06-02T*****",            "current_stage": {                "id": 5057743,                "title": "Reviewing"            },            "custom_fields": [],            "decision": null,            **"labels": [{                    "id": 1124354,                    "name": "Jerusalem"                },                {                    "id": 132456,                    "name": "Testing Stuff"                }],**            "notes": [                {                    "id": 536590,                    "author": {                        "id": 3342356287,                        "first_name": "Brett",                        "last_name": "Wallace",                        "email": "[email protected]"                    },我可以使用以下代碼僅提取我需要的字段:for application in r['results']:        print(application['id'],application['labels'])我得到的東西看起來像這樣:18318202 [{'id': 109135, 'name': 'Jerusalem'}, {'id': 109198, 'name': 'Testing Stuff'}]   11233443 [{'id': 109135, 'name': 'Nazareth'}, {'id': 109198, 'name': 'Age Requirement'}]有沒有辦法讓我只返回 ['labels'] 字段中帶有“Jerusalem”的值?換句話說,查看上面的示例,它只會返回第一行,因為第二行不包含耶路撒冷一詞。我可以從數據中過濾此信息(條件打印語句)或將其提取到新列表中,但我無法弄清楚如何僅獲取其中包含“耶路撒冷”的值。我找到的所有資源都討論了如何加載和轉換數據,但事后沒有過濾掉。提前感謝任何人的時間和支持!
查看完整描述

1 回答

?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

filtered_data = [(application['id'], application['labels']) for application in  
                 r['results'] if 'Jerusalem' in
                 (item['name'] for item in application['labels'])]

也許這也會起作用

filtered_data = [(application['id'], application['labels']) for application in  
                 r['results'] if application['labels'][0]['name'] == 'Jerusalem']


查看完整回答
反對 回復 2023-09-05
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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