处理typeError:不可用的类型:' list'从获取单个项目转换为获取列表时

发布于 2025-02-09 06:58:52 字数 3269 浏览 2 评论 0原文

我正在尝试从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']用于数据中的硬币]get_data()方法中,它的工作正常。但是现在我想获取4个数据点,因此我切换到使用coins = [[COIN ['symbol'],Coin ['name'],Coin ['Market_cap'],Coin ['Market_cap_rank' ]]用于数据中的硬币]。那就是typeError:不可用的类型:'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"
  }

I am trying to fetch data from a JSON endpoint. It doesn't work anymore now that I have switched from fetching just one data value coin['id'] to fetching multiple ones. I have this code:

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()

When I was initially fetching just one data point from the JSON object using
coins = [coin['id'] for coin in data] in the get_data() method, it was working just fine. But now I want to fetch 4 data points so I switched to fetching a list using coins = [[coin['symbol'], coin['name'], coin['market_cap'], coin['market_cap_rank']] for coin in data]. That is when the TypeError: unhashable type: 'list' error started coming up with the following trace:

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'

How can I resolve this so that instead of initially printing just the coin['id'], I can also print the coin['name'],coin['market_cap'], coin['market_cap_rank']?

The JSON endpoint is an object where each item in the list has the following structure:

{
    "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"
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

骷髅 2025-02-16 06:58:52

get_data()返回listcoins.update(checker.get_data(url))试图将该list代码>在set中。但是set项目需要为 hashable ,而list s却不是。如果您返回元组而不是list一切都可以。

要查看差异,请尝试

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

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

get_data() returns a list, and coins.update(Checker.get_data(url)) tries to put that list in a set. But set items need to be hashable, and lists are not. If you return a tuple instead of a list everything will be ok.

To see the difference just try

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

versus

x = set(([1,2])) #ok
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文