Discuss / Python / Marvin_ITer作业,列表生成式

Marvin_ITer作业,列表生成式

Topic source

自己做个记录,感觉L5的切片处理还是很有用的吧。

# -*- coding: UTF-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s,str)==True]
L3 = [s.lower() if isinstance(s,str) else s for s in L1]
L4 = [s.upper() if isinstance(s,str) is True else s for s in L3]
L5 = [s[:1].upper()+s[1:].lower() if isinstance(s,str) else s for s in L4]
print('L1:',L1)
print('L2:',L2)
print('L3:',L3)
print('L4:',L4)
print('L5:',L5)

结果:

L1: ['Hello', 'World', 18, 'Apple', None]
L2: ['hello', 'world', 'apple']
L3: ['hello', 'world', 18, 'apple', None]
L4: ['HELLO', 'WORLD', 18, 'APPLE', None]
L5: ['Hello', 'World', 18, 'Apple', None]

切片确实很神奇


  • 1

Reply