我試圖根據多個條件用Python來過濾一個Json陣列。我的Json類似于這樣(沒有根名稱):
{
"id"。"123455",
"outter": {
"inner": [
{
"nox": "abc:6666",
"code": "1329"。
}
],
},
"主題": {
"reference": "excel"。
},
"date1": "1990-07-28T03:52:44-04:00",
"finalDate": "1990-07-28T03:52:44-04:00"
}
{
"id": "123435",
"outter": {
"inner": [
{
"nox": "abc:6666",
"code": "9351"。
}
],
},
"主題": {
"reference": "excel"。
},
"date1": "1990-07-28T03:52:44-04:00",
"finalDate": "1995-07-28T03:52:44-04:00"
我的目標是根據2個條件進行過濾,并回傳所有符合這些條件的資料。
1: outter --> inner --> code = 9351 AND
2:finalDate >= 1995
到目前為止,我可以用下面的代碼單獨做這個檢查,沒有問題:
data = pd.read_json('myFile.ndjson', lines = True)
for item in data['outter'] 。
for x in item['inner']。
if(x['code'] == '9351')。
found....
但不確定如何同時進行這兩項作業,因為我必須以data['outter']或data['finalDate']開始回圈,而在回圈中我只能看到陣列中的那個元素,而不是整個陣列。
希望得到任何幫助,謝謝!
uj5u.com熱心網友回復:
這里有一個解決方案,可以按照提到的方法過濾串列。我使用了串列理解而不是回圈,其中可能有一些可以改進的地方,但結果似乎至少符合預期。
注意:這使用了 Python 3.8 中引入的 Walrus := 運算子。如果你在一個較早的 Python 版本中運行,你也許可以洗掉使用它的代碼,但在這種情況下,我并沒有太在意。
from pprint import pprint
data_list = [
{
"id"。"123455",
"outter": {
"inner": [
{
"nox": "abc:6666",
"code": "1329"。
}
],
},
"主題": {
"reference": "excel"。
},
"date1": "1990-07-28T03:52:44-04:00",
"finalDate": "1990-07-28T03:52:44-04:00"
},
{
"id": "123435",
"outter": {
"inner": [
{
"nox": "abc:6666",
"code": "9351"。
}
],
},
"主題": {
"reference": "excel"。
},
"date1": "1990-07-28T03:52:44-04:00",
"finalDate": "1995-07-28T03:52:44-04:00"
}
]
結果 = [d for d in data_list
if (year := d['finalDate'][:4]).isnumeric() and year >= '1995>
and any(str(inner['code']) == '9351'
for inner in d['outter']['inner'] or [] )]
pprint(result)
@ted提出了一個很好的觀點:可讀性很重要,所以我有一些時間回去把它寫成一個典型的回圈格式(與上面的邏輯基本相同)。我還做了很多評論,希望能澄清代碼中發生的事情,希望你覺得有幫助:-)
。from pprint import pprint
from typing import Dict, List
結果 = []
# Looping over each dictionary in list[/span]。
for d in data_list:
# 抓取年份部分,`finalDate`的前四個字符。
year = d['finalDate'] [:4]
# isnumeric()以確認年份部分是一個整數。
# then check if string (now confirmed to be numeric) has a higher
# ASCII值是否高于1995。
valid_year = year.isnumeric() and year >= '1995'
# Simple, if it doesn't match our desired year then continue;
# 與下一個回圈迭代。
if not valid_year:
繼續。
# 獲取內部串列,然后在其上回圈。
inner_list。List[Dict] = d['outter'/span>]['inner'/span>]
for inner in inner_list:
if inner['code] == '9351':
# We found an inner with our desired code!
break.
# for-else的語法是不言自明的。這個`else`陳述句是
# 只有當我們沒有`break`出上面的回圈時才運行。
else。
# 沒有運行break陳述句,所以所需代碼不匹配。
# 任何元素。同樣,繼續進行下一次迭代。
continue
# 在這一點上,我們知道它是有效的,因為它同時匹配了我們的。
# 條件,所以我們將其添加到結果串列中。
result.append(d)
# Print the result, but it should be the same # Print the result.
pprint(result)
uj5u.com熱心網友回復:
嘗試像這樣的東西。根據你的需要改變過濾器 :)
for item in data:
if item['finalDate'].startswith("1995") 。
for inner in item['outter']['inner'] 。
if inner['code'] == '9351':
print( item)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/322406.html
標籤:
下一篇:Perl簡單的FIFO計算
