Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将键值列表转换为数组?_Python_Python 3.x - Fatal编程技术网

Python 如何将键值列表转换为数组?

Python 如何将键值列表转换为数组?,python,python-3.x,Python,Python 3.x,我有一个这样的键值对列表 [ { "date": "2020/9/15", "amount": "10", "desc": "test 1" }, { "date": "2020/9/16", "amount": &

我有一个这样的键值对列表

[
    {
        "date": "2020/9/15",
        "amount": "10",
        "desc": "test 1"
    },
    {
        "date": "2020/9/16",
        "amount": "25",
        "desc": "test 2"
    }
]
我想用Python把它转换成这样

[
    ["date", "amount", "desc"],
    ["2020/9/15", "10", "test 1"],
    ["2020/9/16", "25", "test 2"]
]
我需要做一个循环来做这个吗? 有人能给我一个更好的方法吗


非常感谢。

这似乎是一个可以通过Pandas库提供的数据帧处理优雅地处理的问题


请参阅:

您可以选择以下内容:

lis = [
    {
        "date": "2020/9/15",
        "amount": "10",
        "desc": "test 1"
    },
    {
        "date": "2020/9/16",
        "amount": "25",
        "desc": "test 2"
    }
]

out = [list(lis[0])] + [list(dic.values()) for dic in lis]
print(out)
输出:

[['date', 'amount', 'desc'], 
['2020/9/15', '10', 'test 1'], 
['2020/9/16', '25', 'test 2']]

使用熊猫:

import pandas as pd

data = [
    {
        "date": "2020/9/15",
        "amount": "10",
        "desc": "test 1"
    },
    {
        "date": "2020/9/16",
        "amount": "25",
        "desc": "test 2"
    }
]
df = pd.DataFrame(data)
output =  [df.columns.to_list()] + df.values.tolist()
输出

[['date', 'amount', 'desc'],
['2020/9/15', '10', 'test 1'],
['2020/9/16', '25', 'test 2']]

您可以将其添加为注释too@Karthik谢谢你的建议。不幸的是,“新投稿人”标签不允许我评论任何其他人的帖子,因为50%的声誉是这一行动的最低要求。将来我会记住它。
list(dicts[0])+[list(d.values())for d in dicts]
工作得很好(尽管在python-3的早期版本中,在规定字典顺序之前,它可能无法按预期工作)。