[英]Combining lists and lists in dictionary
I have a dictionary where each value is a list of variables (all variables are floats): 我有一本字典,其中每个值都是变量列表(所有变量都是浮点数):
d = {1:[a,b,c], 2:[d,e,f], 3:[g,h,i]}
and a list with the same number of elements as there are elements in the combined lists of the dictionary: 以及具有与字典组合列表中的元素相同数量的元素的列表:
L = [1,2,3,4,5,6,7,8,9]
I want to combine the list into the dictionary, such that: 我想将列表合并到字典中,例如:
d = {1:[a+1,b+2,c+3], 2:[d+4,e+5,f+6], 3:[g+7,h+8,i+9]}
What is a good way to do this? 什么是这样做的好方法?
Here is a way to do it. 这是一种方法。
As your question was unclear about what a
, b
and so on were supposed to be when you first asked your question, I used strings for simplicity. 由于您的问题不清楚您初次提出问题时
a
, b
等应该是什么,因此我使用字符串来简化操作。 It would work all the same with floats. 浮点数将完全相同。
d = {1:['a', 'b', 'c'], 2:['d', 'e', 'f'], 3:['g', 'h', 'i']}
L = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
L_iter = iter(L)
new_d = {key: [val + next(L_iter) for val in sublist] for key, sublist in d.items()}
print(new_d)
# {1: ['a1', 'b2', 'c3'], 2: ['d4', 'e5', 'f6'], 3: ['g7', 'h8', 'i9']}
We create the new dict with a dict comprehension. 我们用dict理解来创建新的dict。 Inside it, we create the new sublist with a list comprehension, iterating on
L
with the help of the iterator L_iter
, which allows to get the next item of L
each time. 在其中,我们创建一个具有列表理解的新子列表,借助迭代器
L_iter
在L
上进行迭代,该迭代器L_iter
都可以获取L
的下一项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.