Re: [問題] 語法改進

看板Python作者 (Dv)時間9年前 (2014/10/11 23:13), 9年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串7/7 (看更多)
以下是我想到的解法,歡迎大家看完後一起討論 XD gist 版 : https://gist.github.com/wdv4758h/1f4090ee9b0035dbcee0 # 路過玩玩 XD # 以下都以 Python 3 為考量,而且以 zip 為出發點來解這個問題。 ''' 如果是一個完整 n x m 的資料, 類似的工作可以用 zip 就完成。 ''' data = [range(10) for i in range(8)] def transpose(data): return zip(*data) for i in transpose(data): print(i) ''' 現在的狀況不是完整 n x m 的資料,而是長短不一的, 一種解是用 itertools 裡的 zip_longest, 參數是 iterables 還有 fillvalue (預設是 None), fillvalue 會拿來填滿資料短缺的部份。 ''' import itertools as it def transpose(data): return it.zip_longest(*data) # 跟前面文章借測資 data = [list(range(i)) for i in range(10, 0, -1)] del data[3] del data[6] for i in transpose(data): print(i) ''' 這邊會把不夠的地方都補 None, 所以輸出會是: (0, 0, 0, 0, 0, 0, 0, 0) (1, 1, 1, 1, 1, 1, 1, None) (2, 2, 2, 2, 2, 2, None, None) (3, 3, 3, 3, 3, 3, None, None) (4, 4, 4, 4, 4, None, None, None) (5, 5, 5, 5, None, None, None, None) (6, 6, 6, None, None, None, None, None) (7, 7, 7, None, None, None, None, None) (8, 8, None, None, None, None, None, None) (9, None, None, None, None, None, None, None) ''' ''' 如果前面那種剛好符合需求,那就可以開心的拿來用了, 如果真的不想要看到多補的那些資料,就再把結果處理過。 ''' def transpose(data): return (tuple(it.filterfalse(lambda x: x is None, i)) for i in it.zip_longest(*data)) for i in transpose(data): print(i) ''' 如此一來結果就變成: (0, 0, 0, 0, 0, 0, 0, 0) (1, 1, 1, 1, 1, 1, 1) (2, 2, 2, 2, 2, 2) (3, 3, 3, 3, 3, 3) (4, 4, 4, 4, 4) (5, 5, 5, 5) (6, 6, 6) (7, 7, 7) (8, 8) (9,) 不過上面處理是以輸入 data 裡沒有 None 為前提的 XD 資料裡面可能有 None 的話就另外用別的值囉。 ''' ※ 引述《rockzerox (Zero)》之銘言: : x 是一個以元素長度排序的list,元素也是list : 也就是x裡有長度不等的list,並且以list長度排列順序 : 最長的list 放在 x[0] 然後越來越短 : 我想直接輸出一行 x[0][0],x[1][0],x[2][0].... : 然後依序輸出 x[0][1],x[1][1],x[2][1].... : 目前想到的作法是 : for i in range(len(x[0])): : try: : print x[0][i]+' '+x[1][i]+' '+x[2][i]+' '+x[3][i]+' '+x[4][i] : except IndexError: : try: : print x[0][i]+' '+x[1][i]+' '+x[2][i]+' '+x[3][i] : except IndexError: : try: : print x[0][i]+' '+x[1][i]+' '+x[2][i] : except IndexError: : try: : print x[0][i]+' '+x[1][i] : except IndexError: : print x[0][i] : 我覺得這有點土法煉鋼 超級白癡.... : 有沒有更好的寫法呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.27.39 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1413040430.A.0A1.html ※ 編輯: wdv4758h (220.141.130.212), 10/11/2014 23:37:09
文章代碼(AID): #1KEKak2X (Python)
討論串 (同標題文章)
文章代碼(AID): #1KEKak2X (Python)