首页 > 解决方案 > 将不同长度列表的 dict 值转换为一个列表

问题描述

我有作为list字典给出的数据。字典listint值是不同长度的值。

[{'values': [876.0]},
 {'values': [823.0]},
 {'values': [828.0]},
 {'values': [838.0]},
 {'values': [779.0]},
 {'values': [804.0, 805.0, 738.0]},
 {'values': [756.0]},
 {'values': [772.0]},
 {'values': [802.0]},
 {'values': [812.0]},
 {'values': [746.0]},
 {'values': [772.0]},
 {'values': [834.0, 844.0]},

我想将所有dict值合二为一(在我的示例代码中list命名)。rr_intervals

[876.0, 823.0, 828.0, 838.0, 779.0, 804.0, 805.0, 738.0, 756.0, 772.0, 802.0, 812.0, 746.0, 772.0, 834.0, 844.0]

我下面的解决方案工作得很好,但是所有嵌套for循环都需要一段时间。我想知道是否会有更优雅的解决方案?

rr_intervals = []
for dictionary in rr_list:
    for key in dictionary:
        if len(dictionary[key]) == 1:
            rr_intervals.append(dictionary[key][0])
        elif len(dictionary[key]) > 1:
            for rr in dictionary[key]:
                rr_intervals.append(rr)

标签: pythonlistdictionaryfor-loop

解决方案


您可以使用列表推导以 Python 方式实现这一目标,

L = [{'values': [876.0]},
     {'values': [823.0]},
     {'values': [828.0]},
     {'values': [838.0]},
     {'values': [779.0]},
     {'values': [804.0, 805.0, 738.0]},
     {'values': [756.0]},
     {'values': [772.0]},
     {'values': [802.0]},
     {'values': [812.0]},
     {'values': [746.0]},
     {'values': [772.0]},
     {'values': [834.0, 844.0]}]

values = [num for d in L for key, value in d.items() for num in value]
print(values)

输出:

[876.0, 823.0, 828.0, 838.0, 779.0, 804.0, 805.0, 738.0, 756.0, 772.0, 802.0, 812.0, 746.0, 772.0, 834.0, 844.0]

推荐阅读