因此,我是这一切的新手,请原谅我不良的格式设置,并且不要轻易掌握术语。
简而言之,我有一个
coins = requests.get("https://bittrex.com/api/v1.1/public/getcurrencies")
返回如下所示的json()嵌套字典(抱歉,短语措词不佳):
{
"success" : true,
"message" : "",
"result" : [{
"Currency" : "BTC",
"CurrencyLong" : "Bitcoin",
"MinConfirmation" : 2,
"TxFee" : 0.00020000,
"IsActive" : true,
"CoinType" : "BITCOIN",
"BaseAddress" : null
}, {
"Currency" : "LTC",
"CurrencyLong" : "Litecoin",
"MinConfirmation" : 5,
"TxFee" : 0.00200000,
"IsActive" : true,
"CoinType" : "BITCOIN",
"BaseAddress" : null
}]
}
简而言之,我想访问其中的每个字典,coins["result"]
并用它们建立我自己的值,以便为每个硬币生成一个类,以便填充继承的代码,例如:
class coinbuilder(self, currency, currencyLong, minConfirmation...):
def __init__(self):
self.currency = currency
self.currencyLong = currencyLong
ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=BTC-" + currency)
我了解此代码是不正确的,但是我想让您了解我要完成的工作。对不起我的措辞,对我来说,这是一般编程的新手,虽然我对函数有一般的了解,但我仍在努力追赶行话。
这是您要执行的操作的总脚本:
import requests
import json
class CoinBuilder:
def __init__(self,dict):
self.currency = dict['Currency']
self.currencyLong = dict['CurrencyLong']
self.minConfirmation = dict['MinConfirmation']
self.txFee = dict['TxFee']
self.isActive = dict['IsActive']
self.coinType = dict['CoinType']
self.baseAddress = dict['BaseAddress']
self.notice = dict['Notice']
coins_response = requests.get("https://bittrex.com/api/v1.1/public/getcurrencies")
all_coins = json.loads(coins_response.content)
list_of_coin_obs = []
for coin in all_coins["result"]:
list_of_coin_obs.append(CoinBuilder(coin))
该脚本获取响应,然后遍历其中的字典result[]
并CoinBuilder
从中构建对象。所有创建的对象也都存储在列表中list_of_coin_obs[]
。
然后,您可以打印出前10个结果,例如,如下所示:
# Print out the first 10 coins
print("First 10 coins:")
for i in range(1,11):
print(i,") ",list_of_coin_obs[i].currency)
对于此示例,将输出:
First 10 coins:
1 ) LTC
2 ) DOGE
3 ) VTC
4 ) PPC
5 ) FTC
6 ) RDD
7 ) NXT
8 ) DASH
9 ) POT
10 ) BLK
如果要创建一种方法来通过其股票代号来查找特定硬币,则可以创建如下所示的内容:
# method to retrieve a specific coin from 'list_of_coin_obs[]'
# we are passing in a parameter, 'coin_abr' to give to our filter
def get_specific_coin_by_abr(coin_abr):
return next(filter(lambda x: x.currency == coin_abr, list_of_coin_obs))
# call our method, which returns a 'CoinBuilder' type
specific_coin = get_specific_coin_by_abr('BTC')
# print our results to show it worked
print('CurrencyName: ',specific_coin.currency,'CurrencyLong: ',specific_coin.currencyLong)
打印:
CurrencyName: BTC CurrencyLong: Bitcoin
注意:这是假设您已经list_of_coin_obs[]
创建了该方法,并且该方法处于同一方法的范围内。
一个建议,这里的类名CoinBuilder
并不完全有意义。类/对象的更好的名称将仅仅是Coin
或NamedCurrency
或其他类似的名称。我想我知道您要干什么,但这可能更适合您的项目。
祝你好运。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句