3 回答
TA贡献1859条经验 获得超6个赞
这应该工作:
data = {
"shopName": "Shop",
"promotions": [
{
"productName": "Cookies",
"oldPrice": 11.99,
"newPrice": 7.99,
"discount": 33
},
{
"productName": "Butter",
"oldPrice": 27.15,
"newPrice": 21.99,
"discount": 19
},
{
"productName": "Milk",
"oldPrice": 30.45,
"newPrice": 21.99,
"discount": 27
}
]
}
MIN_PRICE = 20
filtered_products = [p for p in data['promotions'] if p['discount'] >= MIN_PRICE]
print(filtered_products)
这打印:
[
{
"productName": "Cookies",
"oldPrice": 11.99,
"newPrice": 7.99,
"discount": 33
},
{
"productName": "Milk",
"oldPrice": 30.45,
"newPrice": 21.99,
"discount": 27
}
]
另一种方法是使用filter函数:
filtered_products = list(filter(lambda p: p['discount'] > MIN_PRICE, data['promotions']))
TA贡献1834条经验 获得超8个赞
如果你已经解析了 JSON,你可以使用这个
from typing import Dict, Any
parsed_json = {
"shopName": "Shop",
"promotions": [
{"productName": "Cookies", "oldPrice": 11.99, "newPrice": 7.99, "discount": 33},
{"productName": "Butter", "oldPrice": 27.15, "newPrice": 21.99, "discount": 19},
{"productName": "Milk", "oldPrice": 30.45, "newPrice": 21.99, "discount": 27},
],
}
def find_specific_data(num: int, data: Dict[Any, Any]) -> Dict[Any, Any]:
for value in data["promotions"]:
if value["discount"] > num:
print(value)
find_specific_data(26, parsed_json)
In: find_specific_data(26)
Out: {'productName': 'Cookies', 'oldPrice': 11.99, 'newPrice': 7.99, 'discount': 33}
{'productName': 'Milk', 'oldPrice': 30.45, 'newPrice': 21.99, 'discount': 27}
TA贡献1793条经验 获得超6个赞
试试这个。
import json, pandas as pd
df=pd.DataFrame(json.loads('{ "shopName": "Shop", "promotions": [ { "productName": "Cookies", "oldPrice": 11.99, "newPrice": 7.99, "discount": 33 }, { "productName": "Butter", "oldPrice": 27.15, "newPrice": 21.99, "discount": 19 }, { "productName": "Milk", "oldPrice": 30.45, "newPrice": 21.99, "discount":27 } ]}')['promotions'])
print(df)
productName oldPrice newPrice discount
0 Cookies 11.99 7.99 33
1 Butter 27.15 21.99 19
2 Milk 30.45 21.99 27
print(df[df.discount==df.discount.max()])
productName oldPrice newPrice discount
0 Cookies 11.99 7.99 33
添加回答
举报