簡體   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