列表/列表列表 [英] list of dicts to/from dict of lists

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

问题描述

我希望在列表字典之间来回(全部相同的长度):

I am looking to change back and forth between a dictionary of lists (all of the same length):

DL={'a':[0,1],'b':[2,3]}

和一个字典列表:

LD=[{'a':0,'b':2},{'a':1,'b':3}]

我正在寻找最干净的方式在这两种形式。

I am looking for the cleanest way to switch between the two forms.

推荐答案

也许考虑使用numpy:

Perhaps consider using numpy:

import numpy as np

arr=np.array([(0,2),(1,3)],dtype=[('a',int),('b',int)])
print(arr)
# [(0, 2) (1, 3)]

这里我们访问按名称索引的列,例如'a''b'(类似于 DL ):

Here we access columns indexed by names, e.g. 'a', or 'b' (sort of like DL):

print(arr['a'])
# [0 1]

这里我们通过整数索引来访问行(类似于 LD

$ b

Here we access rows by integer index (sort of like LD):

print(arr[0])
# (0, 2)

行中的每个值都可以通过列名进行访问(类似于 LD ):

Each value in the row can be accessed by column name (sort of like LD):

print(arr[0]['b'])
# 2

这篇关于列表/列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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