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

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'])))  
评论
毛毛虫
毛毛虫

您的代码可以:

price[stock]=price

But that doesn't make any sense. price is a floating point number (calculated in getDataPoint as the average of the bid and ask prices and assigned on the previous line). There's nothing you can index in it. You're also trying to index price['ABC'] and price['DEF'] later in the code, and if you don't fix those too, you'll run into more issues.

I have no idea what you expect price to be at that point. Maybe it's some other variable you've defined elsewhere in the code? If so, you need to change the name of the variable you're currently using for the fourth value you get from getDataPoint.

点赞
评论