Rumah  >  Soal Jawab  >  teks badan

kenaikan biasa python

Yang berikut telah dikumpulkan menggunakan re.sub Anda perlu menambah "1": "2": "3" di hadapan setiap {}. Sila beritahu saya cara menulis ini:

'{"nClass":-1,"nIcon":16},{"nClass":-1,"nIcon":15},{"nClass":-1,"nIcon":14}'

Kesan akhir:

'“1”:{"nClass":-1,"nIcon":16},“2”:{"nClass":-1,"nIcon":15},“3”:{"nClass":-1,"nIcon":14}'
phpcn_u1582phpcn_u15822733 hari yang lalu576

membalas semua(2)saya akan balas

  • 淡淡烟草味

    淡淡烟草味2017-05-18 11:00:27

    Perihalan anda tidak cukup jelas. Anda berkata hasilnya harus menjadi senarai. Adakah anda ingin menukarnya kepada dict?

    import json
    
    str = '{"nClass":-1,"nIcon":16},{"nClass":-1,"nIcon":15},{"nClass":-1,"nIcon":14}'
    lst = json.loads('[{}]'.format(str))
    
    l  = ['"{}":{}'.format(i+1, json.dumps(v)) for i,v in enumerate(lst)]
    print ','.join(l)

    balas
    0
  • 黄舟

    黄舟2017-05-18 11:00:27

    import re
    data = '{"nClass":-1,"nIcon":16},{"nClass":-1,"nIcon":15},   {"nClass":-1,"nIcon":14}'
    # 提取为数组
    data = re.findall('((?=,\s?)?\{.*?\})+', data)
    # 下标从1开始, 所以i+1
    print ','.join(['"%d":%s' % (i+1, v) for i, v in enumerate(data)])
    # "1":{"nClass":-1,"nIcon":16},"2":{"nClass":-1,"nIcon":15},"3":{"nClass":-1,"nIcon":14}

    balas
    0
  • Batalbalas