从解析的API数据进行Python数学运算

2024-06-16 10:13:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个python脚本,它从API(https://api.hypixel.net/skyblock/auctions)中提取数据,它可以很好地完成我想要它做的事情,但是,我想添加一个特性,可以两次找到完全相同的项目,然后比较最低的2个价格(减法),然后显示最低价格和第二个最低价格之间的差异。 例子: 第十项最低价格:100000 第X项第二低价:300000 如果差异为=<;200000,它显示了项目之间的精确差值。 输出:<;项目名称>&书信电报;两个最低价格之间的差价>

这是我现在掌握的密码

import requests

data = requests.get("https://api.hypixel.net/skyblock/auctions").json()
auctions = data["auctions"]
items = []
for auction in auctions:
    try:
        if auction["bin"] and (str(auction["item_name"]).startswith("")) and auction["category"] == "weapon" and auction["tier"] == "EPIC":
            items.append([auction["item_name"], auction["starting_bid"], auction["tier"]])
    except KeyError:
        continue
items.sort(key=lambda x: x[1])
for item in items:
    print(item)

Tags: and项目httpsltgtapinetitems
1条回答
网友
1楼 · 发布于 2024-06-16 10:13:39
import requests

#Here is your new feature calculating the difference between two lowest prices for each item
def func(name, prices):
    prices.sort(reverse = True) #sort prices of an item descending 
    if len(prices) == 1:
        print (f"There is only one price for {name}")
    else:
        print (f"Name : {name}, Price difference between two lowest ones: {prices[-2] - prices[-1]}")

data = requests.get("https://api.hypixel.net/skyblock/auctions").json()
auctions = data["auctions"]
items = []
items1 = {} #Define items1 to group prices of an item in dictionay
for auction in auctions:
    try:
        if auction["bin"] and (str(auction["item_name"]).startswith("")) and auction["category"] == "weapon" and auction["tier"] == "EPIC":
            items.append((auction["item_name"], auction["starting_bid"], auction["tier"]))
            #Find and group all prices for an item
            if auction["item_name"] in list(items1.keys()):
                items1[auction["item_name"]].append(auction["starting_bid"])
            else:
                items1[auction["item_name"]] = [auction["starting_bid"]]
    except KeyError:
        continue
items.sort(key=lambda x: x[1])

#Apply feature for each item
for name,prices in items1.items():
    func(name, prices)

结果如下:

There is only one price for Emerald Blade
There is only one price for Gentle Zombie Commander Whip
There is only one price for Reaper Falchion
Name : Treecapitator, Price difference between two lowest ones: 350000
Name : Heroic Ornate Zombie Sword, Price difference between two lowest ones: 0
There is only one price for Grand Sniper Bow
Name : Spicy Reaper Falchion, Price difference between two lowest ones: 1400000
There is only one price for Unreal Machine Gun Bow ✪✪✪✪✪
There is only one price for Spicy Leaping Sword
There is only one price for Hurricane Bow
There is only one price for Spicy Scorpion Foil
Name : Magma Bow, Price difference between two lowest ones: 535001
There is only one price for Heroic Ornate Zombie Sword ✪✪✪✪✪
There is only one price for Spicy Silk-Edge Sword

相关问题 更多 >