我试图从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:discordbot2.py", line 62, in <module>
Checker(urls, 300)
File "C:discordbot2.py", line 12, in __init__
self.coins = self.get_coins()
File "C:discordbot2.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"
}
get_data()
返回list
,coins.update(Checker.get_data(url))
尝试将list
放在set
中。但是set
项需要是可哈希的,而list
项则不是。如果你返回一个tuple
而不是list
,一切都会好的。
要查看差异,请尝试
x = set([[1,2]]) #error
和
x = set(([1,2])) #ok