Python Avoid Nested For Loop

好久不见. 提交于 2019-12-12 04:08:13

问题


I am new to python programming and I am getting my hands dirty by working on a pet project.

I have tried a lot to avoid these nested for loops, but no success.

Avoiding nested for loops

Returns values from a for loop in python

import requests
import json

r = requests.get('https://api.coinmarketcap.com/v1/ticker/')
j = r.json()


for item in j:
    item['id']
    n = item['id']
    url = 'https://api.coinmarketcap.com/v1/ticker/%s' %n
    req = requests.get(url)
    js = req.json()
    for cool in js:
        print n
        print cool['rank']

Please let me know if more information is needed.


回答1:


Your first request already gets you everything you need.

import requests
import json

response = requests.get('https://api.coinmarketcap.com/v1/ticker/')
coin_data = response.json()

for coin in coin_data:
    print coin['id'] # "bitcoin", "ethereum", ...
    print coin['rank'] # "1", "2", ...
    print coin['price_usd'] # "2834.75", "276.495", ...



回答2:


Question

I have too many loops in loops and want a python way of cleaning it up

Answer

Yes, there is a python way of cleaning up loops-in-loops to make it look better but there will still be loops-in-loops under-the-covers.

import requests
import json

r = requests.get('https://api.coinmarketcap.com/v1/ticker/')
j = r.json()

id_list = [item['id'] for item in j]

for n in id_list:
    url = 'https://api.coinmarketcap.com/v1/ticker/%s' %n
    req = requests.get(url)
    js = req.json()
    print "\n".join([ n+"\n"+item['rank'] for item in js ])

Insight from running this

After running this specific code, I realize that your are actually first retrieving the list of tickers in order of rank using

r = requests.get('https://api.coinmarketcap.com/v1/ticker/')

and then using

url = 'https://api.coinmarketcap.com/v1/ticker/%s' %n

to get the rank.

So long as the https://api.coinmarketcap.com/v1/ticker/ continues to return the items in order of rank you could simplify your code like so

import requests
import json

r = requests.get('https://api.coinmarketcap.com/v1/ticker/')
j = r.json()

id_list = [item['id'] for item in j]

result = zip(id_list,range(1,len(id_list)+1) )

for item in result :
print item[0]
print item[1]

Answer to addition question

Addition question : What if I want one more parameter say price_usd? ..... for cool in js: print n print cool['rank'] print cool['price_usd']

Answer :

change the line

print "\n".join([ n+"\n"+item['rank'] for item in js ])

to

print "\n".join([ n+"\n"+item['rank']+"\n"+cool['price_usd'] for item in js ])


来源:https://stackoverflow.com/questions/44462325/python-avoid-nested-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!