Python避免嵌套For循环

时间:2017-06-09 16:07:48

标签: python loops for-loop nested

我是python编程的新手,我正在通过开展一个宠物项目来解决问题。

我已经尝试了很多以避免这些嵌套for循环,但没有成功。

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']

如果需要更多信息,请与我们联系。

2 个答案:

答案 0 :(得分:1)

问题

循环中有太多循环,需要 python 清理它的方式

答案

是的,有一种python方法可以清理loop-in-loops以使其看起来更好但是仍然会有一个循环中的循环。

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 ])

运行此

的洞察力

运行此特定代码后,我意识到您实际上是第一次使用

按排名顺序检索代码列表
r = requests.get('https://api.coinmarketcap.com/v1/ticker/')

然后使用

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

获得排名。

只要 https://api.coinmarketcap.com/v1/ticker/ 继续以排名顺序返回项目,您就可以简化代码

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]

回答加法问题

添加问题如果我想再多一个参数说price_usd怎么办? .....适用于js的酷炫:打印n打印酷['排名']打印酷[' price_usd']

回答

更改行

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

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

答案 1 :(得分:0)

您的第一个请求已经为您提供了所需的一切。

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", ...