You need to enable JavaScript to run this app. 如何编写函数拆分二维数组中0、1位对应的数值分片
优惠活动
大模型
产品
解决方案
定价
更多

如何编写函数拆分二维数组中0、1位对应的数值分片

二维数组0/1标识分类提取函数实现

功能说明

自定义函数可逐行解析输入二维数组,将每行首位的0/1标识作为分类依据,把对应行的第二个数值拆分归入对应分类的独立分片集合,输出格式和预期效果保持一致。

输入示例

[[0, 38846],
 [1, 51599],
 [0, 51599],
 [1, 52598],
 [0, 290480],
 [0, 360467]]

预期输出效果

Ones = 51599 ,52598
Zeroes = 38846, 51599, 290480, 360467 

实现逻辑

  • 预置两个空列表,分别承载标识为1、标识为0的关联数值
  • 逐行遍历二维数组,提取每行的分类标识和对应数值
  • 匹配标识值,将数值追加到对应分类的列表中
  • 遍历完成后按固定格式拼接两个列表的内容,形成最终输出

参考实现代码(Python)

def split_2d_by_flag(input_arr):
    ones_list = []
    zeroes_list = []
    for row in input_arr:
        flag = row[0]
        val = row[1]
        if flag == 1:
            ones_list.append(str(val))
        elif flag == 0:
            zeroes_list.append(str(val))
    # 按预期格式输出
    print(f"Ones = {','.join(ones_list)}")
    print(f"Zeroes = {','.join(zeroes_list)}")

# 调用测试
test_input = [
    [0, 38846],
    [1, 51599],
    [0, 51599],
    [1, 52598],
    [0, 290480],
    [0, 360467]
]
split_2d_by_flag(test_input)

内容的提问来源于stack exchange,提问作者tony selcuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.05 03:54:08