Re: [问题] 语法改进

楼主: wdv4758h (Dv)   2014-10-11 23:13:46
以下是我想到的解法,欢迎大家看完后一起讨论 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]
: 我觉得这有点土法炼钢 超级白痴....
: 有没有更好的写法呢?

Links booklink

Contact Us: admin [ a t ] ucptt.com