代码如下:
print('\n'.join(' '.join(['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)))
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
写在前面:
1. join方法
- 用于将序列中的元素以指定的字符连接生成一个新的字符串。
str = '-';
seq = ('a','b','c');
print(str.join( seq ))
...
a-b-c
2. 列表生成式:
形如:
list = [x for x in range(5)]
print(list, type(list))
...
[0, 1, 2, 3, 4] <class 'list'>
3. 生成器:
生成器表达式与列表推导非常类似,使用列表推导 会一次产生所有结果。而使用生成器不会一次产生所有结果,它会返回按需产生结果的一个对象。如下所示:
obj = [x ** 2 for x in range(5)]
print(obj, type(obj))
...
[0, 1, 4, 9, 16] <class 'list'>
将列表推导的中括号换成圆括号,就是生成器表达式:
obj = (x ** 2 for x in range(5))
print(obj, type(obj))
...
<generator object <genexpr> at 0x7fe486d59eb8> <class 'generator'>
4. 一行情书 分解 伪代码 如下:
obj3 = ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
obj2 = ' '.join( obj3 ) for x in range(1,10)
obj1 = '\n'.join( obj2 )
print( obj1 )
解析: 层层 开扒:
1.
obj3 = ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
乘法表基本元素构造( x 相当于 九九乘法表 的第x行)
因为 for y in range(1,x+1)
所以需要根据 x 确定 y, 从而 确定 循环几次 继而 生成几个 列表元素
In [16]: x=1
In [17]: ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
Out[17]: ['1 * 1 = 1 ']
In [18]: x=2
In [19]: ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
Out[19]: ['1 * 2 = 2 ', '2 * 2 = 4 ']
In [20]: x=3
In [21]: ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
Out[21]: ['1 * 3 = 3 ', '2 * 3 = 6 ', '3 * 3 = 9 ']
In [22]: x=9
In [23]: ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
Out[23]:
['1 * 9 = 9 ',
'2 * 9 = 18',
'3 * 9 = 27',
'4 * 9 = 36',
'5 * 9 = 45',
'6 * 9 = 54',
'7 * 9 = 63',
'8 * 9 = 72',
'9 * 9 = 81']
2.
obj2 = ' '.join( obj3 ) for x in range(1,10)
for x in range(1,10)
循环遍历x等于(1...10); 每次都会提供给内部一个x;
' '.join( obj3 )
得到一个字符串
In [39]: x=1
In [40]: obj3 = ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
In [41]: ' '.join( obj3 )
Out[41]: '1 * 1 = 1 '
In [42]: x=2
In [43]: ' '.join( obj3 )
Out[43]: '1 * 1 = 1 '
In [44]: obj3 = ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
In [45]: ' '.join( obj3 )
Out[45]: '1 * 2 = 2 2 * 2 = 4 '
In [46]: x=3
In [47]: obj3 = ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
In [48]: ' '.join( obj3 )
Out[48]: '1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 '
In [49]: x=9
In [50]: obj3 = ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
In [51]: ' '.join( obj3 )
Out[51]: '1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81'
3.
obj1 = '\n'.join( obj2 )
换行操作
4.
print( obj1 )
打印