artisan09 2021-02-05 22:16 采纳率: 100%
浏览 99
已采纳

python 列表切片后如何保留其原索引,变换入其它列表呢?

谢谢哦!

  • 写回答

5条回答 默认 最新

  • 歇歇 2021-02-06 18:13
    关注

    开始

     

    import numpy as np
    import time

    采用numpy数组操作,避开循环

     

    def get_index_from_array(from_array, purpose_array):
        purpose_array = np.array(purpose_array)
        from_array = np.array(from_array)
        purpose_idx_in_from = -np.ones(purpose_array.shape).astype(int)     #初始化待返回的索引数组为-1,长度对应purpose_array
        p_idx = np.in1d(purpose_array, from_array)      #筛选出 purpose_array 存在于 from_array 中存在的项
        union_array = np.hstack((from_array, purpose_array[p_idx]))         #合并from_array 和从 purpose_array 中筛选出来的数组
        _, union_idx, union_inv = np.unique(union_array, return_index=True, return_inverse=True)    #unique函数得到索引值
        purpose_idx_in_from[p_idx] = union_idx[union_inv[len(from_array):]] #待返回的索引数组赋值
        return purpose_idx_in_from

    测试

     

    purpose_array = np.array(['b', 't', 'd', 'g', 'f', 'f', 'g', 'b', 'g', 'f', 'p', 'd', 'f', 'r', 'g', 'w', 't', 'd', 'e', 'b', 'e'])
    from_array = np.array(['e', 'c', 'f', 'a', 'e', 'g', 'f', 'a', 'b', 'd', 'd', 'e'])
    idx = get_index_from_array(from_array, purpose_array)
    print(idx)
    pos_idx = (idx != -1)
    test_a = purpose_array[pos_idx]
    test_b = from_array[idx[pos_idx]]
    print((test_a == test_b).all())

    unique函数

     

    from_array = np.array(['e', 'c', 'f', 'a', 'e', 'g', 'f', 'a', 'b', 'd', 'd', 'e'])
    test = np.unique(from_array, True, True, True)
    print(test)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作