问题
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