python - 用于减少重复的循环?
问题描述
我创建了以下代码,它从 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 时遇到问题。
任何指针表示赞赏,这是否是我想要实现的最佳方法
解决方案
像这样的东西可以工作。基本上,只需将重复的部分放在一个函数中,并使用不断变化的参数(货币)调用它。例如,可以使用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))
推荐阅读
- python - 如何将形状 (60,58) (60,59) 的数组更改为相等
- python - 如何在循环中实现气流 DAG
- javascript - 无法理解这个 javascript 解构语句
- c++ - 如何让我的 strchr 函数将 'const char' 和 'char' 数组作为第一个参数?
- java - 如何在 JUnit 5 中使用 mockito 3.0?
- docker - LXC 上的 Docker - rm 文件:注册层失败:处理 tar 文件时出错(退出状态 1):不允许操作
- url - 对页面部分使用非哈希 URL 的优势以及如何实现它们?
- r - 扩展函数在两列之一中返回所有“NA”
- random - AMD FX 8350 上是否有 rdrand 指令?
- json - 使用 json 文件中的 lambda 函数过滤数据以存储在表 JavaFX 中