如何将数组的每个连续元素添加到字典列表的每个元素中?

时间:2021-12-31 14:30:41

I have a list of dictionaries in the form:

我在表单中有一个词典列表:

mylist = [{1: 0.0, 2: 1.0, 3: 2.0},
          {1: 0.0, 2: 2.3, 3: 1.5},
          {1: 0.6, 2: 1.0, 3: 1.0}]

And a list of the form:

以及表格列表:

arr = [[1, 0, 0, 1],
       [1, 0, 2, 1],
       [1.0, 1.1, 3.5, 2.0]]

Length of arr is the same as that of mylist. How can I add each element of arr into their corresponding index elements in mylist so that after insertion, mylist is of the form:

arr的长度与mylist的长度相同。如何将arr的每个元素添加到mylist中相应的索引元素中,以便在插入后,mylist具有以下形式:

mylist = [{1: 0.0, 2 : 1.0, 3: 2.0, 4: 1, 5: 0, 6: 0, 7: 1},
          {1:0.0, 2: 2.3, 3:1.5, 4: 1, 5: 0, 6: 2, 7: 1},
          {1: 0.6, 2: 1.0, 3: 1.0, 4: 1.0, 5: 1.1, 6: 3.5, 7: 2.0}]

1 个解决方案

#1


2  

enumerate each sublist of arr, starting from 4, and update each dictionary.

枚举arr的每个子列表,从4开始,并更新每个字典。

You associate the relevant dictionary with the relevant list by zipping them together with zip:

您可以将相关字典与zip相关联,将相关字典与相关列表相关联:

for d, extra in zip(mylist, arr):
    d.update(enumerate(extra, start=4))

enumerate normally counts from 0:

枚举通常从0开始计数:

>>> list(enumerate([1, 0, 0, 1]))
[(0, 1), (1, 0), (2, 0), (3, 1)]

You want it to count from 4:

你希望它从4开始计算:

>>> list(enumerate([1, 0, 0, 1], start=4))
[(4, 1), (5, 0), (6, 0), (7, 1)]

#1


2  

enumerate each sublist of arr, starting from 4, and update each dictionary.

枚举arr的每个子列表,从4开始,并更新每个字典。

You associate the relevant dictionary with the relevant list by zipping them together with zip:

您可以将相关字典与zip相关联,将相关字典与相关列表相关联:

for d, extra in zip(mylist, arr):
    d.update(enumerate(extra, start=4))

enumerate normally counts from 0:

枚举通常从0开始计数:

>>> list(enumerate([1, 0, 0, 1]))
[(0, 1), (1, 0), (2, 0), (3, 1)]

You want it to count from 4:

你希望它从4开始计算:

>>> list(enumerate([1, 0, 0, 1], start=4))
[(4, 1), (5, 0), (6, 0), (7, 1)]