将长度不一的列表的dict值转换为一个列表 [英] Converting dict values that are list of varying lengths into one list

查看:59
本文介绍了将长度不一的列表的dict值转换为一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据,这些数据作为词典的list给出.字典的值是不同长度的int值中的list.

I have data that was given as a list of dictionaries. The values of the dictionaries are list of int values of varying lengths.

[{'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).

I would like to get all dict values into one list (named rr_intervals in my sample code).

[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循环都花了一段时间.我想知道是否会有更优雅的解决方案?

My solution below worked just fine, but it took a while with all the nested for loops. I was wondering whether there'd be a more elegant solution?

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)

推荐答案

您可以使用列表理解.

rr_intervals = [val for sub_dict in rr_list for val in sub_dict['values']] #rr_list is the list of dictionaries.
# [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]

这篇关于将长度不一的列表的dict值转换为一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆