[当我执行此代码时,出现错误“ float”对象不支持项目分配

问题描述 投票:-1回答:1
import urllib.request
import time
import json
import random
# Server API URLs 
QUERY = "http://localhost:8080/query?id={}"
# 500 server request
N = 500
def getDataPoint(quote):
""" Produce all of the needed values to generate a datapoint """
""" ------------- Update this function ------------- """
    stock = quote['stock']
    bid_price = float(quote['top_bid']['price'])
    ask_price = float(quote['top_ask']['price'])
    price = (bid_price+ask_price)/2
    return stock, bid_price, ask_price, price
def getRatio(price_a, price_b):
""" Get ratio of price_a and price_b """
""" ------------- Update this function ------------- """
""" Also create some unit tests for this function in client_test.py """
    if (price_b==0):
        return
    return price_a/price_b
# Main
if __name__ == "__main__":
# Query the price once every N seconds.
    for _ in range(N):
        quotes = json.loads(urllib.request.urlopen(QUERY.format(random.random())).read())
    """ ----------- Update to get the ratio --------------- """
        for quote in quotes:
            stock, bid_price, ask_price, price = getDataPoint(quote)
            price[stock]=price
            print ("Quoted %s at (bid:%s, ask:%s, price:%2s)" % (stock, bid_price, ask_price, price))
        print ("Ratio %s" % (getRatio(price['ABC'], price['DEF'])))  
python python-3.x urllib3
1个回答
0
投票

您的代码可以:

price[stock]=price

但是那没有任何意义。 price是一个浮点数(在getDataPoint中计算为买入价和要价的平均值,并在前一行中指定)。您无法在其中建立索引。您还尝试稍后在代码中为price['ABC']price['DEF']编制索引,如果您也未解决这些问题,则会遇到更多问题。

我不知道您当时期望price是什么。也许这是您在代码的其他地方定义的其他变量?如果是这样,您需要将当前使用的变量的名称更改为从getDataPoint获得的第四个值。

© www.soinside.com 2019 - 2024. All rights reserved.