[英]Creating multiple dicts using some but not all elements from a pair of lists
I would like, from a pair of lists, say: 我想从一对清单中说:
a = ['str1', 'str2', 'str3', 'str4', 'str5']
b = [var1, var2, var3, var4, var5]
to be able to create multiple dictionaries, with arbitrarily selected pairs of elements from a (as keyword) and b (as value). 能够创建多个字典,并从a(作为关键字)和b(作为值)中任意选择元素对。 I have found in a comment on an answer to this question , the following method: 我在对这个问题的答案的评论中发现以下方法:
full_set = dict(zip(a,b))
subset = {i:full_set[i] for i in a if i not in ['str2', 'str5']}
which produces subset dictionary: 产生子集字典:
{'str1': var1, 'str3': var3, 'str4': var4}
This works fine, but I am curious as to whether there is an equally short or shorter method of building subset dictionaries from the two lists, eg via specifying the list indices for the elements I want included, without creating a full dictionary containing all elements first. 这很好用,但是我对从两个列表中构建子集字典是否有同样短或短的方法感到好奇,例如通过为我要包含的元素指定列表索引,而无需先创建包含所有元素的完整字典。
For context, my vars refer to scikit-learn estimator objects. 对于上下文,我的var指的是scikit-learn估计器对象。
You can combine both statements into one: 您可以将两个语句合并为一个:
avoid = {'str2', 'str5'} # Sets have better lookup time :)
{k:v for k,v in zip(a,b) if k not in avoid}
Probably convert this to numpy arrays and use fancy indexing like this: 可能将其转换为numpy数组,并使用像这样的花式索引:
import numpy as np
a = np.array(['str1', 'str2', 'str3', 'str4', 'str5'])
b = np.array([1,2,3,4,5])
indices = [0, 1, 4]
d = dict(zip(a[indices],b[indices]))
d returns: d返回:
{'str1': 1, 'str2': 2, 'str5': 5}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.