python - 转置行和列

时间:2017-10-10 14:59:24

标签: python matrix transpose

这是我的代码。我是编程新手,所以你能帮我解决一下如何正确地转换行和列吗?

def scytale_encrypt(plain_text, key):

    chars = [c for c in plain_text if c not in (' ',',','.','?','!',':',';',"'")]
    chunks = math.ceil(len(chars)/ float(key))
    inters, i, j = [], 1, 1
    cipher, k = [], 0
    item=[]

    while i <= chunks :
        inters.append(tuple(chars[j-1:(j + key)-1]))
        i += 1
        j += key


    while k < key:
        l = 0
        while l < chunks:
            if k >= len(inters[l])and plain_text.islower():
                cipher.append('z')
            elif k >= len(inters[l]):
                     cipher.append('Z')
            else:
                cipher.append(inters[l][k])
            l += 1
        k += 1
    print (inters)
    return ''.join(cipher);

我的意见  My inpputed plain text and key

1 个答案:

答案 0 :(得分:0)

这是代码&amp;输出:

aMyArray = [ ['a1', 'a2','a3','a4','a5'], ['b1','b2','b3'], ['c1','c2','c3']]

aMyArrayTrsp = []
aMyArrayTemp = []

sRec = ""
iMaxRows = 0
iMaxCols = 0

print "initial array:"
for i in range(len(aMyArray)):
        sRec = ""
        for j in range(len(aMyArray[i])):
                sRec = sRec+","+aMyArray[i][j]
        print sRec

print "Finding max"
iMaxCols = len(aMyArray)
for i in range(len(aMyArray)):
        if(iMaxRows<len(aMyArray[i])):
                iMaxRows = len(aMyArray[i])
print("Max rows="+str(iMaxRows))
print("Max cols="+str(iMaxCols))

print "Creating a blank 2D list.."
for i in range( iMaxRows ):
        aMyArrayTemp = []
        for j in range(iMaxCols ):
                aMyArrayTemp.append("")
        aMyArrayTrsp.append(aMyArrayTemp)

print "transposing.."
for i in range( iMaxRows ):
        for j in range(iMaxCols):
                try:
                        aMyArrayTrsp[i][j]=aMyArray[j][i]
                except IndexError:
                        aMyArrayTrsp[i][j]=""


print "Final output:"
for i in range(len(aMyArrayTrsp)):
        sRec = ""
        for j in range(len(aMyArrayTrsp[i])):
                sRec = sRec+","+aMyArrayTrsp[i][j]
        print sRec

这是输出。

initial array:
,a1,a2,a3,a4,a5
,b1,b2,b3
,c1,c2,c3
Finding max
Max rows=5
Max cols=3
Creating a blank 2D list..
transposing..
Final output:
,a1,b1,c1
,a2,b2,c2
,a3,b3,c3
,a4,,
,a5,,