【问题标题】:Handling a TypeError: unhashable type: 'list' when switching from fetching a single item to fetching a list从获取单个项目切换到获取列表时处理 TypeError: unhashable type: 'list'
【发布时间】:2022-06-21 23:49:01
【问题描述】:

我正在尝试从 JSON 端点获取数据。现在我已经从只获取一个数据值coin['id'] 切换到获取多个数据值,现在它不再起作用了。我有这个代码:

class Checker:
    def __init__(self, urls, wait_time):
        self.wait_time = wait_time
        self.urls = urls
        self.coins = self.get_coins()
        self.main_loop()
    
    @staticmethod
    def get_data(url):
        url = requests.get(url)
        text = url.text
        data = json.loads(text)
        coins = [[coin['symbol'], coin['name'], coin['market_cap'], coin['market_cap_rank']] for coin in data]
        return coins
    
    def get_coins(self):
        coins = set()
        for url in self.urls:
            coins.update(Checker.get_data(url))
        return coins

    def check_new_coins(self):
        new_coins = self.get_coins()
        
        coins_diff = list(new_coins.difference(self.coins))
        coins_out = list((self.coins).difference(new_coins))
        
        current_time = time.strftime("%H:%M:%S", time.localtime())
        
        if len(coins_diff) > 0:
            # print(current_time, coins_diff)
            bot_message = f'New coins alert at {current_time} \n'
            for in_coin in coins_diff:
                bot_message += f'NAME:{in_coin[1]} SYMBOL:{in_coin[0]} MARKET CAP: {in_coin[2]} MARKET RANK:{in_coin[3]}\n'
            print(bot_message)
        else:
            pass
        
        self.coins = new_coins
    
    def main_loop(self):
        while True:
            time.sleep(self.wait_time)
            self.check_new_coins()

当我最初从 JSON 对象中获取一个数据点时,使用 coins = [coin['id'] for coin in data]get_data() 方法中,它工作得很好。但现在我想获取 4 个数据点,所以我切换到使用 coins = [[coin['symbol'], coin['name'], coin['market_cap'], coin['market_cap_rank']] for coin in data] 获取列表。那是TypeError: unhashable type: 'list' 错误开始出现以下跟踪的时候:

Traceback (most recent call last):
  File "C:\discord\bot2.py", line 62, in <module>
    Checker(urls, 300)
  File "C:\discord\bot2.py", line 12, in __init__
    self.coins = self.get_coins()
  File "C:\discord\bot2.py", line 26, in get_coins
    coins.update(Checker.get_data(url))
TypeError: unhashable type: 'list'

我该如何解决这个问题,而不是最初只打印coin['id'],我还可以打印coin['name'],coin['market_cap'], coin['market_cap_rank']

JSON 端点是一个对象,其中列表中的每个项目都具有以下结构:

{
    "id": "bitcoin",
    "symbol": "btc",
    "name": "Bitcoin",
    "image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
    "current_price": 21636,
    "market_cap": 411087658127,
    "market_cap_rank": 1,
    "fully_diluted_valuation": 452613028369,
    "total_volume": 27595965142,
    "high_24h": 21568,
    "low_24h": 19931.52,
    "price_change_24h": 837.49,
    "price_change_percentage_24h": 4.02661,
    "market_cap_change_24h": 15476001610,
    "market_cap_change_percentage_24h": 3.91192,
    "circulating_supply": 19073337,
    "total_supply": 21000000,
    "max_supply": 21000000,
    "ath": 69045,
    "ath_change_percentage": -68.79379,
    "ath_date": "2021-11-10T14:24:11.849Z",
    "atl": 67.81,
    "atl_change_percentage": 31674.91619,
    "atl_date": "2013-07-06T00:00:00.000Z",
    "roi": null,
    "last_updated": "2022-06-21T14:49:06.386Z"
  }

【问题讨论】:

    标签: python json list error-handling typeerror


    【解决方案1】:

    get_data() 返回一个list,而coins.update(Checker.get_data(url)) 尝试将list 放入set。但是set 的项目需要hashable,而lists 不是。如果你返回 tuple 而不是 list 一切都会好的。

    要查看差异,请尝试

    x = set([[1,2]]) #error
    

    x = set(([1,2])) #ok
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 2019-10-11
      • 2020-03-27
      • 2020-05-11
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多