嵌套列表到dict [英] Nested list to dict

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

问题描述

我尝试创建 dict 通过嵌套列表

  groups = [['Group1','A','B'],['Group2','C','D']] 

对于x中的x,如果y = x [0]},对于x中的y,则L = [{y:x [0])对于x中的x,
d = {k:v对于k的L中的d,d中的v, )}

print(d)
{'B':'Group1','C':'Group2','D':'Group2','A'

但似乎有点复杂。



有更好的解决方案吗?

解决方案

如何:



<$对于行[1:]中的k的行,p = p> d = {k:row [0]}

这给出:

 >>> {k:row [0] for row in group for k in row [1:]} 
{'D':'Group2','B':'Group1','C':'Group2',' A':'Group1'}

所以你遍历每个 。该行的第一个元素被视为值( row [0] ),并且迭代 row [1:] 获取所有密钥 k



很奇怪,因为它可能会似乎,这个表达式也可以当你给它一个空行(如 groups = [[],['A','B']] )。那是因为 row [1:] 将是空的,因此行[0] 部分是从不评估:

 >>> groups = [[],['A','B']] 
>>> {k:row [0] for row in group for k in row [1:]}
{'B':'A'}


I try create dict by nested list:

groups = [['Group1', 'A', 'B'], ['Group2', 'C', 'D']]

L = [{y:x[0] for y in x if y != x[0]} for x in groups]
d = { k: v for d in L for k, v in d.items()}

print (d)
{'B': 'Group1', 'C': 'Group2', 'D': 'Group2', 'A': 'Group1'}

But it seems a bit complicated.

Is there a better solution?

解决方案

What about:

d = {k:row[0] for row in groups for k in row[1:]}

This gives:

>>> {k:row[0] for row in groups for k in row[1:]}
{'D': 'Group2', 'B': 'Group1', 'C': 'Group2', 'A': 'Group1'}

So you iterate over every row in the groups. The first element of the row is taken as value (row[0]) and you iterate over row[1:] to obtain all the keys k.

Weird as it might seem, this expression also works when you give it an empty row (like groups = [[],['A','B']]). That is because row[1:] will be empty and thus the row[0] part is never evaluated:

>>> groups = [[],['A','B']]
>>> {k:row[0] for row in groups for k in row[1:]}
{'B': 'A'}

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

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