栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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可以是切片)的方便操作,所以只能暂时用这个效率不太高的小函数来操作了。还望有经验的大佬指点一二~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/445644.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号