我有一個 python 字典串列(假設每個字典暫時都是平的)。鍵都是字串,值是字串或實數。我希望用戶可以自由地使用某種查詢語言以他們選擇的任何方式過濾這個 dict。查詢可以包含嵌套的“和”和/或“或”。
實作(或最好重用)我可以在應用程式內部安全執行的語言/語法的最佳方法是什么(不安全的選項是使用 eval)?
例如:
list_of_dicts = [
{"type":"a", "val1": 10, "val2": 12.2, "val3": "off"},
{"type":"b", "val1": 230, "val2": 15.5, "val3": "on"},
{"type":"c", "val1": 40, "val3": "off"},
{"type":"a", "val1": 60, "val2": 52.0, "val4": 12},
{"type":"c", "val1": 80, "val2": 18.1},
]
用戶應該能夠說:
“給我所有型別為 a 或 b 的專案。從結果串列中,給我所有 val3 關閉的情況”
翻譯成:
cond = lambda x: x.get("type") in ["a", "b"] and x.get("val3") == "off"
resultant = [a for a in list_of_dicts if cond(a)]
# Out: [{'type': 'a', 'val1': 10, 'val2': 12.2, 'val3': 'off'}]
uj5u.com熱心網友回復:
使用Pandas和query方法。Python 是一種表達性語言,所以為什么不使用它。
import pandas as pd
df = pd.DataFrame(list_of_dicts)
out = df.query("""type.isin(['a', 'b']) and val3 == 'off'""")
print(out)
# Output
type val1 val2 val3 val4
0 a 10 12.2 off NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404585.html
標籤:
上一篇:更新字典中的值串列(累積更新)
