![](/img/trans.png)
[英]In a dataframe with both positive & negative numbers, how to round positive numbers up and round negative numbers down (both to multiples of 5)?
[英]How to improve this pattern of checking if two numbers are both positive or negative?
我发现自己大量创建了这种模式:
for _x, _y in zip(x, y):
if _x > 0 and _y > 0:
something += 1
elif _x < 0 and _y < 0:
something += 1
else:
something -= 1
我只是觉得必须有一种比这更好的pythonic方式。 这是一个非常简单的算法,感觉就像在浪费时间输入所有内容。
那么,我该如何改善呢?
编辑:关于重复的问题,这与此无关。 这不是我如何创建所需逻辑的问题,该逻辑已经存在于我的问题中。 我要问的是如何改进我使用的模式。
我能想到的唯一改进是:
for _x, _y in zip(x, y):
something += 1 if _x * _y > 0 else -1
for _x, _y in zip(x, y):
if _x * _y > 0:
something += 1
else:
something -= 1
在我看来,您的代码已经很好,不需要改进:
无论如何,如果要降低圈复杂度 ,可以将if条件外部化:
def evaluate_zipped(x,y):
if (x > 0 and y > 0) or (x < 0 and y < 0):
return 1
else:
return -1
for _x, _y in zip(x,y):
something += evaluate_zipped(_x, _y)
如果您正在寻找单线飞机,则可以map
您的决策声明:
something += sum(map(lambda _x,_y: 1 if _x*_y > 0 else -1, x,y))
无论如何,我还是建议避免使用单行代码,因为这样会使您失去可读性,却一无所获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.