从JSON fi的元素生成列表

2024-10-01 15:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个JSON文件(https://www.dropbox.com/s/woxtqy634g89f0r/tags.json?dl=0)中列出三个不同的列表,比如a、B和C:

A: (13,13,...,37)
B: (12,14,...,32)
C: ([-1.3875, 1.3875, -1.95 ], [[-2.775, -0., -0., ], .., [-0., 2.775, -0. ]])

有什么快速而聪明的方法吗?你知道吗

我在jupyter笔记本上试过:

with open('tags.json', 'r') as f:
    tags = json.load(f)
tags['neb.00']

输出会给我

'13->12 0.2906332796567428 [-1.3875 1.3875 -1.95 ]'

然后我可以做一些类似于tags['neb.03'][0:2]的事情来获得13等等。但这不是一个好的方法,我希望有一个适当的方法来做。有人能帮我吗?你知道吗


Tags: 文件方法httpscomjson列表wwwwith
2条回答
import json
import re

with open('tags.json', 'r') as f:
    tags = json.load(f)

A = []
B = []
C = []
for x in sorted(tags.keys()):
    m = re.search(r'(\d+)->(\d+) (\d+\.\d+) \[(.+)\]', tags[x])
    if not m:
        print("Not matching:", tags[x])
        continue
    A.append(int(m.group(1)))
    B.append(int(m.group(2)))
    C.append([float(y) for y in m.group(4).split()])

sorted()或其他函数,如果您需要以确定的方式对项目进行排序。你知道吗

for k,v in data.items():
    A =v[:v.index('-')]
    B =v[v.index('>')+1:v.index('[')]
    C =v[v.index('[')::]
    print(k,A,B,C)

.items()遍历dict键(k)和值(v)

我不知道这是否是你想要的答案,但看看你的数据,它似乎有一个稳定的结构。我想您可以将每个值附加到一个列表中。你知道吗

相关问题 更多 >

    热门问题