【问题标题】:Trying to calculate profit to return to my website试图计算利润以返回我的网站
【发布时间】:2025-12-08 11:05:03
【问题描述】:

我正在计算你是否会从游戏中的两个项目中获利,现在我需要做 “NPC买价-卖价*640”,原因是你只能买640的物品,而且首先我需要保证金,这就是NPC买价-卖价的原因。

这就是我的 python 的样子:

@app.route('/bresell')
def reSell():
    farmingMerchantPrices = [
        "5",  # cocoa beans
        "12",  # brown mushroom
        "2.33",  # carrot
        "8",  # pumpkin
        "2.33",  # wheat
        "12",  # red mushroom
        "2.33",  # potato
        "4",  # sand
        "5",  # sugar cane
        "2",  # melon
    ]
    farmingMerchantName = [
        "Cocoa Beans",
        "Brown Mushroom",
        "Carrot",
        "Pumpkin",
        "Wheat",
        "Red Mushroom",
        "Potato",
        "Sand",
        "Sugar Cane",
        "Melon"
    ]
    sellPrice = []
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[not allowed to show key]').json()
    for x in farmingProducts:
        sellPrice.append(f["products"][x]["sell_summary"][0]["pricePerUnit"])
    profit = []
    for x in farmingMerchantPrices:
        profit.append(sellPrice - x)
    return render_template('resell.html', farmingMerchantPrices=farmingMerchantPrices, farmingMerchantName=farmingMerchantName, sellPrice=sellPrice, profit=profit)

这是我的 HTML:

<tbody>
      {% for name, npcBuy,price,profit in zip(farmingMerchantName,
      farmingMerchantPrices,sellPrice,profit) %}
      <tr>
        <td>{{ name }}</td>
        <td>{{ profit will go here }}</td>
        <td>{{ npcBuy }}</td>
        <td>{{ price }}</td>
      </tr>
      {% endfor %}
    </tbody>

如果我应该在 Jinja 或烧瓶中做数学,我有点困惑,烧瓶对吗?而且我有点不确定该怎么做!

【问题讨论】:

  • 最好在后端进行任何计算(这里是烧瓶)。所以,你是对的
  • 是的,因为我认为我的“npcBuy”是一个字符串,而我的“利润”是一个浮点值,所以在尝试将它们相互减去时,我遇到了一些问题.. 或你能把两个数组相减吗?如果我附加了sellprice(我有),然后我附加了“farmingMerchantPrices”,我可以用“sellPrice”中的第一项减去“farmingMerchantPrices”中的第一项吗?
  • 我尝试关注this 线程,但出现错误:TypeError: unsupported operand type(s) for -: 'str' and 'float'

标签: python flask jinja2


【解决方案1】:

要回答您的第一个问题,最好在您的计算被隐藏且安全的后端执行任何计算。

根据您的第二个问题,我认为您的代码的唯一问题是您将farmingMerchantPrices 中的价格定义为字符串而不是数字。所以,你的问题应该通过改变类型来解决:

farmingMerchantPrices = [
        5,  # cocoa beans   (5 instead of "5")
        12,  # brown mushroom
        2.33,  # carrot
        8,  # pumpkin
        2.33,  # wheat
        12,  # red mushroom
        2.33,  # potato
        4,  # sand
        5,  # sugar cane
        2,  # melon
    ]

【讨论】:

  • 哦,好吧,我试过了,然后这样做了:for i in range(amount): profit = farmingMerchantPrices[i] - sellPrice[i],将“利润”返回到我的 HTML,然后出现错误:TypeError: 'float' object is not iterable
  • 开个玩笑!修复它,必须做:
  • profit = [] zip_object = zip(farmingMerchantPrices, sellPrice) for farmingMerchantPrices_i, sellPrice_i in zip_object: profit.append(farmingMerchantPrices_i - sellPrice_i)