Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

python - For loop for reduce duplication?

I've created the following code, that pulls Cryptocurrency prices from the CoinGecko api and parses the bits I need in 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"])

This works fine, except I then need to duplicate the above 4 lines for every currency which is getting long/messy & repetitive.

After researching I felt an approach was to store the coins in an array, and loop through the array replacing bitcoin in the above example with each item from the array.

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

This works as expected, but I'm having issues substituting bitcoin/btc for x successfully.

Any pointers appreciated, and whether this is the best approach for what I am trying to achieve

question from:https://stackoverflow.com/questions/65885198/for-loop-for-reduce-duplication

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this could work. Basically, just put the repeated part inside a function and call it with the changing arguments (currency). The substitution of the currency can be done for example with 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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...