首页 > 解决方案 > 用于减少重复的循环?

问题描述

我创建了以下代码,它从 CoinGecko api 中提取加密货币价格并解析我在 JSON 中需要的位

btc = requests.get("https://api.coingecko.com/api/v3/coins/bitcoin")
btc.raise_for_status()
jsonResponse = btc.json() # print(response.json()) for debug
btc_marketcap=(jsonResponse["market_data"]["market_cap"]["usd"])

这很好用,除了我需要为每一种变得冗长/混乱和重复的货币复制上述 4 行。

经过研究,我觉得一种方法是将硬币存储在一个数组中,然后循环遍历数组,用数组中的每个项目替换上面示例中的比特币。

symbols = ["bitcoin", "ethereum", "sushi", "uniswap"]
for x in symbols:
    print(x)

这按预期工作,但我在成功用比特币/btc 代替 x 时遇到问题。

任何指针表示赞赏,这是否是我想要实现的最佳方法

标签: python

解决方案


像这样的东西可以工作。基本上,只需将重复的部分放在一个函数中,并使用不断变化的参数(货币)调用它。例如,可以使用f-strings替换货币:

def get_data(currency):
    btc = requests.get(f"https://api.coingecko.com/api/v3/coins/{currency}")
    btc.raise_for_status()
    return btc.json()["market_data"]["market_cap"]["usd"]
    
for currency in ["bitcoin", "ethereum", "sushi", "uniswap"]:
    print(get_data(currency))

推荐阅读