Py学习  »  pX0r  »  全部回复
回复总数  2

解析任意json树的python、递归和函数方法:

handlers = {
    list:  iterate,
    dict:  delve,
    str:   emit_li,
    float: emit_li,
}

def emit_li(stuff, strong=False):
    emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
    print(emission % stuff)

def iterate(a_list):
    print('<ul>')
    map(unravel, a_list)
    print('</ul>')

def delve(a_dict):
    print('<ul>')
    for key, value in a_dict.items():
        emit_li(key, strong=True)
        unravel(value)
    print('</ul>')

def unravel(structure):
    h = handlers[type(structure)]
    return h(structure)

unravel(data)

哪里 数据 是一个python列表(从json文本字符串解析):

data = [
    {'data': {'customKey1': 'customValue1',
           'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
  'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
               'viewport': {'northeast': {'lat': 37.4508789,
                                          'lng': -122.0446721},
                            'southwest': {'lat': 37.3567599,
                                          'lng': -122.1178619}}},
  'name': 'Mountain View',
  'scope': 'GOOGLE',
  'types': ['locality', 'political']}
]
8 年前
回复了 pX0r 创建的主题 » 在python3中如何将单词向后翻转?在这种情况下[副本]

一个不那么令人费解的方法是:

string = 'happy'
print(string)

“快乐”

string_reversed = string[-1::-1]
print(string_reversed)

“碧波”

英语中[-1::-1]读作:

“从-1开始,一直走,采取-1的步骤”