2 条题解

  • 0
    @ 2026-3-26 17:44:03

    NUMPY045 题解:替换最大值

    题目

    创建大小为 10 的随机向量,将最大值替换为 0。

    解题思路

    找到最大值的索引,然后设置为 0。

    代码

    import numpy as np
    Z = np.random.random(10)
    Z[Z.argmax()] = 0
    print(Z)
    

    代码详解

    1. np.random.random(10) —— 创建 10 个随机数
    2. Z.argmax() —— 返回最大值的索引
    3. Z[idx] = 0 —— 将最大值设为 0

    argmax 原理

    Z = [0.3, 0.8, 0.1, 0.9, 0.4]
    #       0     1     2     3     4
    # 最大值是 0.9,索引是 3
    
    Z.argmax()  # 3
    Z.max()     # 0.9
    

    其他方法

    # 方法2:使用布尔索引
    Z[Z == Z.max()] = 0
    
    # 方法3:使用 np.where
    Z[np.where(Z == Z.max())[0][0]] = 0
    
    # 方法4:全部替换为0
    Z[Z >= Z.max()] = 0  # 如果有多个最大值
    

    核心知识点

    1. argmax() —— 最大值的索引
    2. argmin() —— 最小值的索引
    3. 布尔索引 —— Z[条件]
    • 0
      @ 2026-3-25 15:38:39

      NumPy045 题解

      参考代码

      import numpy as np
      Z = eval(input())
      n = int(input())
      print(np.where(np.arange(len(Z)) < n, 'A', 'B'))
      
      • 1

      信息

      ID
      96
      时间
      1000ms
      内存
      256MiB
      难度
      (无)
      标签
      (无)
      递交数
      0
      已通过
      0
      上传者