我想篩選下方詞典串列,以獲得pg_noS表示,其將在所有詞典text中包含valid。
test_response = [
{
'title': 'some value',
'pg_no': 1,
'text': 'Data is not valid'
},
{
'title': 'another title',
'pg_no': 2,
'text': 'some random text'
},
{
'title': 'last title',
'pg_no': 3,
'text': 'valid data'
}
]
uj5u.com熱心網友回復:
以下理解有效:
pg_nos = [d["pg_no"] for d in test_response if "valid" in d["text"]]
# [1, 3]
uj5u.com熱心網友回復:
你可以試試下面的代碼
for i in test_response:
if "valid" in i['text']:
print(i['pg_no']) #Perform your required operation here I just used print for display
或者你也可以像這樣使用串列理解
[print(i['pg_no']) for i in test_response if "valid" in i['text']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/318290.html
