代碼如下:
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
寫(xiě)在前面:
1. join方法
- 用于將序列中的元素以指定的字符連接生成一個(gè)新的字符串碰镜。
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. 生成器:
生成器表達(dá)式與列表推導(dǎo)非常類(lèi)似酥诽,使用列表推導(dǎo) 會(huì)一次產(chǎn)生所有結(jié)果。而使用生成器不會(huì)一次產(chǎn)生所有結(jié)果疑苫,它會(huì)返回按需產(chǎn)生結(jié)果的一個(gè)對(duì)象。如下所示:
obj = [x ** 2 for x in range(5)]
print(obj, type(obj))
...
[0, 1, 4, 9, 16] <class 'list'>
將列表推導(dǎo)的中括號(hào)換成圓括號(hào),就是生成器表達(dá)式:
obj = (x ** 2 for x in range(5))
print(obj, type(obj))
...
<generator object <genexpr> at 0x7fe486d59eb8> <class 'generator'>
4. 一行情書(shū) 分解 偽代碼 如下:
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 )
解析: 層層 開(kāi)扒:
1.
obj3 = ['%s * %s = %-2s' % (y,x,x*y) for y in range(1,x+1)]
乘法表基本元素構(gòu)造( x 相當(dāng)于 九九乘法表 的第x行)
因?yàn)?for y in range(1,x+1)
所以需要根據(jù) x 確定 y, 從而 確定 循環(huán)幾次 繼而 生成幾個(gè) 列表元素
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)
循環(huán)遍歷x等于(1...10); 每次都會(huì)提供給內(nèi)部一個(gè)x;
' '.join( obj3 )
得到一個(gè)字符串
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 )
打印