繁体   English   中英

字典值的列表理解,根据值分配0或1

[英]list comprehension for dictionary values, assigning 0 or 1 based on value

我想使用列表推导根据字典中的值创建一个0和1s的向量。

在此示例中,我希望将每个正数都返回为1,而将每个0数保持为0。但是,我需要更改解决方案,以便如果我要将阈值设置为0.25(而不是0),则可以轻松地使更改。

test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}
skill_vector = [1 for skill.values() in test_dict if skill.values > 0 else 0]

所需的输出:[1,0,1,1]

编辑:明智的人指出,字典没有顺序,因此输出将不可用。 鉴于此,我打算使用OrderedDict子类。

您可以将测试中的布尔值转换为int,而不是使用if/else模式:

test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}

threshold = 0
[int(v > threshold) for v in test_dict.values()]
# [1, 0, 1, 1]

假设您使用的是python版本,该版本将密钥保持在插入顺序中。

您可以使用三元运算符:

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}
>>> [1 if x > 0 else 0 for x in test_dict.values()]
[1, 0, 1, 1]

您还可以使用字典理解来确保将结果映射到正确的键:

>>> {k:1 if v > 0 else 0 for k,v in test_dict.items()}
{'a': 1, 'b': 0, 'c': 1, 'd': 1}

如果要使用skill_values函数:

def skill_values(x):
     return skill_values >= .25

skill_vector = [1 if skill_values(x) else 0 for x in test_dict.values()]

或将映射合并到另一个答案中的int

skill_vector = [int(skill_values(x)) for x in test_dict.values()]

码:

test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}
skill_vector = list(map(int, map(bool, test_dict.values())))

输出:

[1, 0, 1, 1]

暂无
暂无

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

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