gpt4 book ai didi

python - 展平包含列表和元组列表的字典

转载 作者:行者123 更新时间:2023-11-28 17:56:55 25 4
gpt4 key购买 nike

from numpy import nan
d = {'E1': (((((['C', 'Me', 'Lans'], float(nan), ['3050', '55901']),
float(nan)),
float(nan)),
['2011-09-05 00:00:00', '3050-09-02 00:00:00']),
['2011-09-05 00:00:00', '3050-09-02 00:00:00']),
'E2': (((((['Can', 'Mar', 'Horns'], ['26D']),
['1001', '14086']),
float(nan),
['(100) 300-2345']),
['1001-09-02 00:00:00', '0100-09-02 00:00:00', '2011-19-26 00:00:00']),
['1001-09-02 00:00:00', '0100-09-02 00:00:00', '2011-19-26 00:00:00'])}

我有一个看起来很乱的字典 d。我想要以下输出,其中 d 是字典中的列表

d = {'E1': ['C', 'Me', 'Lans', float(nan),'3050', '55901', float(nan)), float(nan), '2011-09-05 00:00:00', '3050-09-02 00:00:00',
'2011-09-05 00:00:00', '3050-09-02 00:00:00'],
'E2': ['Can', 'Mar', 'Horns', '26D','1001', '14086', float(nan),'100 300-2345','1001-09-02 00:00:00', '0100-09-02 00:00:00', '2011-19-26 00:00:00',
'1001-09-02 00:00:00', '0100-09-02 00:00:00', '2011-19-26 00:00:00']}

我试过代码 Flatten nested dictionaries, compressing keys但它并没有给我我正在寻找的东西。任何机构都可以提供帮助吗?

最佳答案

您可以使用递归地展平列表和元组的函数:

def flatten(o):
return [s for i in o for s in flatten(i)] if isinstance(o, (list, tuple)) else [o]

因此 {k: flatten(v) for k, v in d.items()} 返回:

{'E1': ['C',
'Me',
'Lans',
nan,
'3050',
'55901',
nan,
nan,
'2011-09-05 00:00:00',
'3050-09-02 00:00:00',
'2011-09-05 00:00:00',
'3050-09-02 00:00:00'],
'E2': ['Can',
'Mar',
'Horns',
'26D',
'1001',
'14086',
nan,
'(100) 300-2345',
'1001-09-02 00:00:00',
'0100-09-02 00:00:00',
'2011-19-26 00:00:00',
'1001-09-02 00:00:00',
'0100-09-02 00:00:00',
'2011-19-26 00:00:00']}

关于python - 展平包含列表和元组列表的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57765022/

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