列表推导式总共有两种形式:
示例
1-100中3的倍数
p = [x for x in range(1,101) if x%3 == 0]
p值列表为:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93
, 96, 99]
#1-100中,不是3的倍数的数去相反数,其余的数保持不变
q = [x if x%3==0 else -x for x in range(1,101)]
q值列表为:
[-1, -2, 3, -4, -5, 6, -7, -8, 9, -10, -11, 12, -13, -14, 15, -16, -17, 18, -19, -20, 21, -22, -23, 24, -25, -26, 27, -2
8, -29, 30, -31, -32, 33, -34, -35, 36, -37, -38, 39, -40, -41, 42, -43, -44, 45, -46, -47, 48, -49, -50, 51, -52, -53,
54, -55, -56, 57, -58, -59, 60, -61, -62, 63, -64, -65, 66, -67, -68, 69, -70, -71, 72, -73, -74, 75, -76, -77, 78, -79,
-80, 81, -82, -83, 84, -85, -86, 87, -88, -89, 90, -91, -92, 93, -94, -95, 96, -97, -98, 99, -100]
示例
s= [m + n +l for m in 'ABC' for n in 'DEF' for l in 'HIJ']
s列表为:
['ADH', 'ADI', 'ADJ', 'AEH', 'AEI', 'AEJ', 'AFH', 'AFI', 'AFJ', 'BDH', 'BDI', 'BDJ', 'BEH', 'BEI', 'BEJ', 'BFH', 'BFI',
'BFJ', 'CDH', 'CDI', 'CDJ', 'CEH', 'CEI', 'CEJ', 'CFH', 'CFI', 'CFJ']
多层for写法:
for m in 'ABC':
for n in 'DEF':
for l in 'HIJ':
print(m+n+l,end=' ')
打印:
ADH ADI ADJ AEH AEI AEJ AFH AFI AFJ BDH BDI BDJ BEH BEI BEJ BFH BFI BFJ CDH CDI CDJ CEH CEI CEJ CFH CFI CFJ