gpt4 book ai didi

python - 如何从列表列表中制作有序字典?

转载 作者:太空狗 更新时间:2023-10-29 22:16:21 26 4
gpt4 key购买 nike

问题是:有一个名称列表和一个列表列表,如何创建一个列表,其中每个项目都是一个有序的字典,名称作为键,列表列表中的项目作为值?从下面的代码中可能会更清楚:

from collections import OrderedDict

list_of_lists = [
['20010103', '0.9507', '0.9569', '0.9262', '0.9271'],
['20010104', '0.9271', '0.9515', '0.9269', '0.9507'],
['20010105', '0.9507', '0.9591', '0.9464', '0.9575'],
]

names = ['date', 'open', 'high', 'low', 'close']

我想得到:

ordered_dictionary = [
OrderedDict([('date', '20010103'), ('open', '0.9507'), ('high', '0.9569'), ('low', '0.9262'), ('close', '0.9271')]),
OrderedDict([('date', '20010104'), ('open', '0.9271'), ('high', '0.9515'), ('low', '0.9269'), ('close', '0.9507')]),
OrderedDict([('date', '20010105'), ('open', '0.9507'), ('high', '0.9591'), ('low', '0.9464'), ('close', '0.9575')]),
]

最佳答案

使用zip()组合名称和值。通过列表理解:

from collections import OrderedDict

ordered_dictionary = [OrderedDict(zip(names, subl)) for subl in list_of_lists]

给出:

>>> from pprint import pprint
>>> pprint([OrderedDict(zip(names, subl)) for subl in list_of_lists])
[OrderedDict([('date', '20010103'), ('open', '0.9507'), ('high', '0.9569'), ('low', '0.9262'), ('close', '0.9271')]),
OrderedDict([('date', '20010104'), ('open', '0.9271'), ('high', '0.9515'), ('low', '0.9269'), ('close', '0.9507')]),
OrderedDict([('date', '20010105'), ('open', '0.9507'), ('high', '0.9591'), ('low', '0.9464'), ('close', '0.9575')])]

关于python - 如何从列表列表中制作有序字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15382807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com