简体   繁体   English

高效地将一个很长的json数组转换成对应的list

[英]Efficiently convert a long json array to the corresponding list

I could have a very long and variable json object like below (the length of the object could varry)我可以有一个非常长且可变的 json object 如下所示(object 的长度可能会有所不同)

{
'1': 230,
'2':240,
'3':100,
'4':20,
...
'670000':100
}

I need to convert above JSON object to a simple unit8 array while keeping the order of elements without saving the indexes我需要将上面的 JSON object 转换为一个简单的 unit8 数组,同时保持元素的顺序而不保存索引

[230,240,100,20,...,100]

well, I come up with below solution using genrators好吧,我想出了以下使用发电机的解决方案

def f(js):
...    for x in js:
...        yield js[x]
[x for x in f(js)]

But I wonder why if there is a more efficient solution as well?但我想知道为什么还有更有效的解决方案?

You can create a generator that steps through the items of a dictionary.您可以创建一个遍历字典项的生成器。

The dict.values() method will return a view object that reflects the current object. dict.values dict.values()方法将返回一个反映当前 object 的视图object。

def values_of(obj):
    for value in obj.values():
        yield value

data = {
    '1': 230,
    '2': 340,
    '3': 100,
    '4': 20,
    '670000': 100
}

print(list(values_of(data)))

Simply turn it into python dictionary and append every value to the list like the following只需将其转换为 python 字典和 append 列表中的每个值,如下所示

data = {
'1': 230,
'2':340,
'3':100,
'4':20,
'670000':100
}
print([i for i in data.values()])

output output

[230, 340, 100, 20, 100]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM