[英]How to do logical operation in Python dictionary?
I have the following dictionary.我有以下字典。
dct = {'hello':1.9,'ciao':1.5,'yes':-2,'no':-3}
I would like to replace positive values with 1 and negative values with -1.我想用 1 替换正值,用 -1 替换负值。
I tried many codes, one of which below:我尝试了很多代码,其中之一如下:
np.where(dct.values() > 0, 1, 0)
np.where(dct.values() > 0, -1, 0)
However, it did not manage to make it work.然而,它并没有让它发挥作用。 How can I do it?我该怎么做?
Thanks!谢谢!
You could achieve this with a dict comprehension (not sure how you want to handle exactly equal to zero, if you expect that to occur)您可以通过 dict 理解来实现这一点(如果您希望发生这种情况,不确定您想如何处理完全等于零)
>>> d = {'hello': 1.9,'ciao': 1.5,'yes': -2,'no': -3}
>>> {k: 1 if v > 0 else -1 for k, v in d.items()}
{'hello': 1, 'ciao': 1, 'yes': -1, 'no': -1}
The conditional expression条件表达式
1 if v >= 0 else -1
is maybe the most intelligible, but there are some shorter options :-)可能是最容易理解的,但有一些更短的选择:-)
(v >= 0) - (v < 0)
2 * (v >= 0) - 1
(1, -1)[v < 0]
from math import copysign as cs
cs(1, v) # if you are ok with floats
just to list a few.只是列举几个。 Of course, all of them can plugged into the dict comprehension:当然,所有这些都可以插入到 dict 理解中:
dct = {k: cs(1, v) for k, v in dct.items()}
This can also be done using math.copysign
although is probably a bit overboard for a small application otherwise I would use what others have posted.这也可以使用math.copysign
完成,尽管对于小型应用程序来说可能有点过分,否则我会使用其他人发布的内容。
>>> from math import copysign
>>> {k: int(copysign(1, v)) for k, v in dct.items()}
{'hello': 1, 'ciao': 1, 'yes': -1, 'no': -1}
Here is your answer:这是你的答案:
{k: 1 if v > 0 else -1 for k, v in dict.items()}
Do not use dict as variable name, by the way.顺便说一下,不要使用 dict 作为变量名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.