Python 3 - for循环结果的打印顺序

时间:2017-11-04 22:53:23

标签: python

我在Python 3.6中编写了一个脚本,该脚本查询API数据以从邮政编码返回邮政地址。

脚本如下:

import requests
import urllib.parse 

main_api = 'http://link.to.api_site/json?'
key = 'AbCdEfGhIjKlMnOpQrStUvWxYz0123456789'
address = '90210'

url = main_api + urllib.parse.urlencode({'address':address, 'key':key})

json_data = requests.get(url).json()

for result in json_data["results"][0]["address_components"]:
    print(result["long_name"])

问题在于给出了JSON数据的顺序。当我从Web浏览器运行查询时,将显示数据:

{
   "results" : [
     {
     "address_components" : [
        {
           "long_name" : "90210",
           "short_name" : "90210",
           "types" : [ "postal_code" ]
        },
        {
           "long_name" : "Beverly Hills",
           "short_name" : "Beverly Hills",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Los Angeles County",
           "short_name" : "Los Angeles County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        }

所以当For循环运行时,它按以下顺序返回数据:

90210
Beverly Hills
Los Angeles County
California
United States

我更喜欢的是以不同的顺序打印地址:

Beverly Hills
Los Angeles County
California
United States
90210

所以问题是,有没有办法在打印For循环的结果时更改顺序。

2 个答案:

答案 0 :(得分:1)

一种简单的方法是将每个信息存储到变量中,然后以正确的顺序打印每个内容:

import requests
import urllib.parse 

main_api = 'http://link.to.api_site/json?'
key = 'AbCdEfGhIjKlMnOpQrStUvWxYz0123456789'
address = '90210'

url = main_api + urllib.parse.urlencode({'address':address, 'key':key})

json_data = requests.get(url).json()

area_code = json_data["results"][0]["address_components"][0]["long_name"]
area = json_data["results"][0]["address_components"][1]["long_name"]
county = json_data["results"][0]["address_components"][2]["long_name"]
state = json_data["results"][0]["address_components"][3]["long_name"]
country = json_data["results"][0]["address_components"][4]["long_name"]

print(area)
print(county)
print(state)
print(country)
print(area_code)

你也可以打印列表的内容,除了第一个,然后"手动"第一个。

也许是这样的? (我不确定这是否有效,我还没有测试过它。)

for result in json_data["results"][0]["address_components"][1:]:
    print(result["long_name"])
print(json_data["results"][0]["address_components"][1]["long_name"])

答案 1 :(得分:0)

你可以试试这样的事情;

order_to_print = ["locality", "administrative_area_level_2", "administrative_area_level_1", "country", "postal_code"]

for order in order_to_print:
    for result in json_data["results"][0]["address_components"]:
        if result["types"][0] == order:
            print(result["long_name"])

但我认为如果不定义上述顺序就不可能。