本文實例講述了Python實現讀取字符串按列分配后按行輸出。分享給大家供大家參考,具體如下:
問題:
輸入一個字符串和一個數字,數字代表分為幾行,需要按照給定的列存儲方法存儲下來之后按行拼接讀出,如:
輸入:TNGDWXAZQSCVBK,3
輸出:TWQBNDXZSVKGAC
中間轉化的時候會形成這樣的圖形:
T W Q K
N D X Z S V B
G A C
化為矩陣可能看得更清晰一點:
T 0 W 0 Q 0 B
N D X Z S V K
G 0 A 0 C 0 0
0是作為空白填充進去的,下面看具體的實現:
#!usr/bin/env python#encoding:utf-8'''''__Author__:沂水寒城功能:zigzag_patternT W Q KN D X Z S V BG A Cconvert("TNGDWXAZQSCVBK", 3) should return "TWQBNDXZSVKGAC".'''def convert_test(one_str,num): ''''' ''' mod=len(one_str)%(num+1) if mod==0: cols=(len(one_str)/(num+1))*2 else: cols=(len(one_str)/(num+1))*2+1 rows=num #print 'rows, cols', rows, cols matrix=[] for i in range(rows): matrix.append([0]*cols) one_str_list=list(one_str) for j in range(cols): if j%2==0: for i in range(rows): if len(one_str_list): matrix[i][j]=one_str_list.pop(0) else: matrix[1][j]=one_str_list.pop(0) #print matrix # for one in matrix: # one_list=[str(onec) for onec in one] # print ' '.join(one_list) res='' for one_list in matrix: one_list=[str(one) for one in one_list] res+=''.join(one_list) return ''.join(res.split('0'))if __name__ == '__main__': print convert_test("TNGDWXAZQSCVBK", 3) print convert_test("PAYPALISHIRING", 2) print convert_test("PAYPALISHIRING", 4)結果如下:
TWQBNDXZSVKGAC
PPIINAYALSHRIG
PLRAAIIIYSNPHG
[Finished in 0.3s]
更多關于Python相關內容可查看本站專題:《Python字符串操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答