列出字典值的理解,根据值指定0或1

2024-06-17 12:54:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用列表理解来根据字典中的值创建0和1的向量。你知道吗

在本例中,我希望每个正数都返回为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子类。你知道吗


Tags: intest列表forif字典阈值解决方案
3条回答

您可以将测试中的布尔值强制转换为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}

代码:

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]

相关问题 更多 >