You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python set存储列表报TypeError: unhashable type: 'list'排查解决

报错根因

Python的set集合仅支持存储**可哈希(不可变类型)**的元素:

  • 最初你仅提取coin['id']字符串存入集合,字符串是不可变类型,因此运行正常
  • 修改后你返回的每个元素是list嵌套列表,列表属于可变类型,不支持哈希计算,因此执行coins.update()往集合写入列表时触发TypeError: unhashable type: 'list'
  • 额外注意:你提取的market_cap、market_cap_rank是实时变动的字段,如果直接把这些字段作为集合对比的依据,会因为数值波动反复误报新增/下架币种,必须用每个币种固定不变的id字段作为差异判断的唯一标识。
修复步骤
  1. 把单条币种数据的存储结构从可变的list改为不可变的tuple(元组),满足集合的哈希要求,同时把固定id字段加入返回值,作为差异判断的唯一键
  2. 拆分数据存储逻辑:用单独的集合存所有币种的id,专门用来做新旧数据差集计算;用字典做id到多字段详情的映射,专门用来读取字段拼接告警消息,彻底避免动态字段变动导致的误判。
修复后完整代码
import requests
import json
import time

class Checker:
    def __init__(self, urls, wait_time):
        self.wait_time = wait_time
        self.urls = urls
        self.coin_ids, self.coin_detail_map = self.get_coins()
        self.main_loop()
    
    @staticmethod
    def get_data(url):
        resp = requests.get(url)
        data = resp.json()
        # 用元组替代列表,第一个元素存固定id作为唯一标识
        coins = [
            (coin['id'], coin['symbol'], coin['name'], coin['market_cap'], coin['market_cap_rank'])
            for coin in data
        ]
        return coins
    
    def get_coins(self):
        coin_id_set = set()
        coin_detail_map = {}
        for url in self.urls:
            coin_list = Checker.get_data(url)
            for coin in coin_list:
                coin_id = coin[0]
                coin_id_set.add(coin_id)
                coin_detail_map[coin_id] = coin
        return coin_id_set, coin_detail_map

    def check_new_coins(self):
        new_coin_ids, new_coin_detail_map = self.get_coins()
        
        # 仅通过固定id做差集对比,避免市值、排名变动导致误判
        new_added_ids = new_coin_ids.difference(self.coin_ids)
        removed_ids = self.coin_ids.difference(new_coin_ids)
        
        current_time = time.strftime("%H:%M:%S", time.localtime())
        
        if len(new_added_ids) > 0:
            bot_message = f'New coins alert at {current_time} \n'
            for cid in new_added_ids:
                coin_info = new_coin_detail_map[cid]
                # 元组索引:0=id 1=symbol 2=name 3=market_cap 4=market_cap_rank
                bot_message += f'NAME:{coin_info[2]} SYMBOL:{coin_info[1]} MARKET CAP: {coin_info[3]} MARKET RANK:{coin_info[4]}\n'
            print(bot_message)
        
        # 更新本地缓存的最新数据
        self.coin_ids = new_coin_ids
        self.coin_detail_map = new_coin_detail_map
    
    def main_loop(self):
        while True:
            time.sleep(self.wait_time)
            self.check_new_coins()

内容的提问来源于stack exchange,提问作者Tendekai Muchenje

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:18:25