Turning a list of lists into a dictionary of lists

时光毁灭记忆、已成空白 提交于 2019-12-11 19:26:55

问题


Hi there I am having a small problem with a code I am trying to implement. I wish to convert a list of lists into a dictionary where the keys refer to the lists position in the original list of lists, and the values are a list of the items that were in said list (from the original list of lists). I also wish to remove all of the Nones present in the original list of lists. For example:

[[(1, None), (2, None)], [(0, None), (2, None)], [(1, None), (0, None)]]

I would want this to become:

{0: [1, 2], 1: [0, 2], 2: [1, 0]}

回答1:


Looks like a basic dict and list comprehension

raw = [[(1, None), (2, None)], [(0, None), (2, None)], [(1, None), (0, None)]]
print {i: [el[0] for el in l] for i, l in enumerate(raw)}

prints

{0: [1, 2], 1: [0, 2], 2: [1, 0]}



回答2:


Just for fun, if you wanted to use lambda and map:

dict(map(lambda i: (li.index(i), [i[0][0], i[1][0]]), li))

An alternative dictionary comprehension which uses the index method instead of enumerate:

{li.index(i):[el[0] for el in i] for i in li}


来源:https://stackoverflow.com/questions/29323121/turning-a-list-of-lists-into-a-dictionary-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!