一个九九乘法口诀表,引出优雅的python

中规中矩的写法,思路是两个循环,换行或tab,字符串格式化打印:

 1 def multi99():
 2     result = ''
 3     for i in range(1, 10):
 4         for j in range(1, i + 1):
 5             separator = '\n' if j == i else '\t'
 6             result += '%d * %d = %-2d' % (j, i, i * j)
 7             result += separator
 8     return result
 9 
10 print(multi99())

优美的python写法,生成式表达+两个循环+换行或tab,字符串格式化打印,lambda表达式,字符串的join,一句代码搞定:

1 print(''.join(['%d * %d = %-2d'%(y,x,x*y)+(lambda x,y:'\n' if x == y else '\t')(x,y) for x in range(1,10) for y in range(1,x+1)]))

 

posted @ 2018-10-23 20:35  tintinsoft  Views(926)  Comments(0Edit  收藏  举报