大家好,正如你在我的代码中看到的,我得到了最小的价格值但问题是我无法将其余的数据与最低价格联系起来,例如Ingame_name和status,特别是最低价格的状态:
以为例,我们取这个条目url:https://api.warframe.market/v1/items/mirage_prime_systems/orders?include=item
作为结果,我们将得到很多开放的订单从JSON链接,我需要做的事情在这里是获得最小的价格从一个在线玩家与他的所有基本信息的用户。
这是我的代码
import requests
import json
item = input('put your item here please : ')
gg = item.replace(' ', '_')
response_url = requests.get(f'https://api.warframe.market/v1/items/'+ gg +'/orders?include=item')
data = json.loads(response_url.text)
orders = data["payload"]["orders"]
min_price = min(o["platinum"] for o in orders if o["order_type"] == "sell")
print(min_price)
和我似乎我不能做,除非你帮助我,伙计们,我真的很感激。
您可以使用内置min()
与自定义key
。当您需要对初始数据应用一些过滤时,有两种可能的方法:
- 在搜索最小之前过滤数据(此答案中显示的一种可能方法);
- 利用python中使用的字典比较来比较序列(docs)。
我发现第二种方法更好,因为它可以只迭代一次所有的顺序(更有效)。
所以要实现这一点,我们应该从lambda
返回,我们将传递给min()
不仅"platinum"
键值,而且布尔结果倒转条件.
为什么倒?因为我们在寻找最小值。这意味着我们的lambda
的每次返回都将与之前的最小值进行比较。在python中,False
等于0,True
等于1
(docs)。0 < 1
,所以如果任何一个反转条件是True
,所有的键都将大于"platinum"
的值。
代码:
import requests
from json import JSONDecodeError
item = input("Put your item here please: ")
try:
response = requests.get("https://api.warframe.market/v1/items/" +
item.lower().replace(" ", "_") + "/orders",
params={"include": "item"})
json_data = response.json()
orders = json_data["payload"]["orders"]
except requests.RequestException as e:
print("An error occurred during processing request:", e)
except JSONDecodeError:
print("Server response is not valid json:", response.text)
except KeyError as e:
print("Response doesn't contain", e, "key")
except Exception as e:
print("Unexpected error:", e)
else:
min_price_order = min(orders, key=lambda x: (x["order_type"] != "sell",
x["user"]["status"] != "ingame",
x["platinum"]))
print(min_price_order)
按订单类型筛选列表,并使用lambda查找最小值
orders = [{'order_type':'sell','other':88,'platinum':4},
{'order_type':'sell','other':77,'platinum':9},
{'order_type':'buy','other':88,'platinum':4}]
min_price = min([o for o in orders if o["order_type"] == "sell"],key= lambda x : x ['platinum'])
print(min_price)
输出{'order_type': 'sell', 'other': 88, 'platinum': 4}