求实现数组正负元素数量相等且无零的简易编码方案
简洁实现正负数量相等且无零的数组处理
Got it, let's solve this problem with a clean, concise approach. The core requirements are straightforward: the final array must have an equal number of positive and negative elements, with no zeros allowed. Here's a streamlined implementation that handles uneven positive/negative counts and filters out zeros in one go:
Python 实现示例
def balanced_positive_negative(arr): # 一次遍历完成零过滤+正负分组 positives = [] negatives = [] for num in arr: if num > 0: positives.append(num) elif num < 0: negatives.append(num) # 取两组中较小的长度,作为最终保留的元素数量 keep_count = min(len(positives), len(negatives)) # 拼接并返回平衡后的数组 return positives[:keep_count] + negatives[:keep_count]
逻辑说明
- 高效遍历:只需要一次遍历数组,同时完成零过滤和正负元素分组,比先过滤再分组的写法更高效。
- 自动平衡:通过
min()直接锁定能保留的最大相等数量,确保最终数组正负元素数完全一致。 - 保留原顺序:截取前
keep_count个元素的方式会保留原数组中正负元素的相对顺序,如果不需要固定顺序,也可以添加random.shuffle(result)来打乱(记得先导入random模块)。
极致简洁的一行式(可选)
如果追求代码最短,也可以用列表推导式组合实现(性能差异可忽略):
def balanced_pos_neg(arr): pos = [x for x in arr if x > 0] neg = [x for x in arr if x < 0] k = min(len(pos), len(neg)) return pos[:k] + neg[:k]
内容的提问来源于stack exchange,提问作者AlexH
相关产品推荐
相关产品推荐

