Python 取三维列表特定行列页的元素

据笔者目前所知,python 中的矩阵没有matlab中的矩阵用起来舒服,比如想从一个三维矩阵中取出特定行列页的元素。笔者写了一个小函数来实现取三维列表特定行列页的元素,贴在这里以备后用。

def getDataFrom3list(Data,a=[],b=[],c=[],tag=0):
    """
    get the specfic elements of specfic raw, cloum, page in 3D-list.
    
    > @param[in] Data:          The 3D-list
    > @param[in] a:             The raw index
    > @param[in] b:             The column indx
    > @param[in] c:             The page indx
    > @param[in] tag:           result id
    return:     
    < @param[out] tmp1:         1D-list, when the tag is 0
    < @param[out] tmp2:         3D-list, when the tag is not 0
    """
    z=len(Data)             #page
    h=len(Data[0])          #raw
    l=len(Data[0][0])       #column
    tmp1=[]
    tmp2=[]
    if len(a)==0:
        a=list(range(0,h))
    if len(b)==0:
        b=list(range(0,l))
    if len(c)==0:
        c=list(range(0,z))
    for i in c:
        hldata=Data[i]
        tmpc=[]
        for j in a:
            ldata=hldata[j]
            tmpb=[]
            for k in b:
                tmp1.append(ldata[k])
                tmpb.append(ldata[k])
            tmpc.append(tmpb)
        tmp2.append(tmpc)
    if tag==0:
        return tmp1
    else:
        return tmp2

这个函数第一个传入参数是一个三维list,第二个传入参数是所需元素行的索引,第三个传入参数是所需元素列的索引,第四个传入参数是所需元素页的索引,第四个传入参数是结果标识,0表示返回一个一维list,1表示返回一个三维度list。


使用示例:

c=[[[111,121,131,141],
[211,221,231,241],
[311,321,331,341]],
[[112,122,132,142],
[212,222,232,242],
[312,322,332,342]],
[[113,123,133,143],
[213,223,233,243],
[313,323,333,343]]]
print(c)
d=gr.getDataFrom3list(c,[0,1,2],[1,2,3],[1,2],1)
print(d)

返回结果

[[[122, 132, 142], 
[222, 232, 242], 
[322, 332, 342]], 
[[123, 133, 143], 
[223, 233, 243], 
[323, 333, 343]]] 

示例数据是一个3*4*33行4列3页的列表。

据笔者目前所知 python 中没有类似matlab中m(i,j,k)(i,j,k可以是切片)的方便操作,所以只能暂时用这个效率不太高的小函数来操作了。还望有经验的大佬指点一二~

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流浪猪头拯救地球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值