简体   繁体   English

将嵌套的列表列表转换成字典

[英]Convert nested list of lists into a dictionary

I have an array of lists that I need to turn into a dictionary where the first element in each list is a key and the remaining elements are values corresponding to that key. 我有一个列表数组,需要将其变成字典,其中每个列表中的第一个元素是键,其余元素是与该键对应的值。

For example, the array: 例如,数组:

 a=[[[1, 2, 4] [2, 1, 3, 5] [3, 2, 6]]
   [[4, 1, 5, 7] [5, 2, 4, 6, 8] [6, 3, 5, 9]]]

should look like: 应该看起来像:

 dict = {1:[2,4], 2:[1,3,5], 3:[2,6], 4:[1,5,7], 5:[2,4,6,8], 6:[3,5,9]}

While the object looks like a list of lists, it is actually an array created by this process: 尽管该对象看起来像一个列表列表,但实际上是通过此过程创建的数组:

 a = [[i] for i in range(1, 10)]
     swap = a[0]
     a[0] = None
     b = np.array(a)
     b[0] = swap
     b.shape = 3, 3

Then I looped through the array and appended numbers to the different list elements which is why the lists have expanded. 然后,我遍历数组并将数字附加到不同的列表元素,这就是列表已扩展的原因。 Let me know if that's not clear! 让我知道是否不清楚!

Is there an easy way to loop through an array and create this? 有没有一种简单的方法可以遍历数组并创建数组? Thanks! 谢谢!

You can use nested dict comprehension with extended iterable unpacking : 您可以将嵌套的dict理解与扩展的可迭代解压缩结合使用

>>> l = [[[1, 2, 4], [2, 1, 3, 5], [3, 2, 6]], [[4, 1, 5, 7], [5, 2, 4, 6, 8], [6, 3, 5, 9]]]
>>> {k: v for sub_l in l for k, *v in sub_l}
{1: [2, 4], 2: [1, 3, 5], 3: [2, 6], 4: [1, 5, 7], 5: [2, 4, 6, 8], 6: [3, 5, 9]}

Using generator to flatten the list, 使用生成器展平列表,

a=[
     [[1, 2, 4], [2, 1, 3, 5], [3, 2, 6], ],
     [[4, 1, 5, 7], [5, 2, 4, 6, 8], [6, 3, 5, 9]],

   ]

def flat(a):
    for level1 in a:
        for level2 in level1:
            yield level2

result = {}
for l in flat(a):
    result[l[0]] = l[1:]

print result

Here is another solution based on @niemmi answer using itertools.chain() maybe more readable: 这是另一个使用itertools.chain()基于@niemmi答案的解决方案,可能更具可读性:

>>> import itertools
>>> l = [[[1, 2, 4], [2, 1, 3, 5], [3, 2, 6]], [[4, 1, 5, 7], [5, 2, 4, 6, 8], [6, 3, 5, 9]]]
>>> {k: v for k, *v in itertools.chain.from_iterable(l)}
{1: [2, 4], 2: [1, 3, 5], 3: [2, 6], 4: [1, 5, 7], 5: [2, 4, 6, 8], 6: [3, 5, 9]}

Now we got only one for loop by flatten the l list. 现在for通过平整l列表,我们只有一个for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM