Discuss / Python / 交作业

交作业

Topic source

loveprruy

#1 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

L1 = ['Hello', 'World',18,'Apple',None]
L2=[]
for s in L1:
    if isinstance(s,str):
        L2.append(s.lower())
print(L2)

把上面的程序简化,如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

L1 = ['Hello', 'World',18,'Apple',None]
L2=[n.lower() for n in [s for s in L1 if isinstance(s,str)]]
print(L2)

loveprruy

#2 Created at ... [Delete] [Delete and Lock User]

可以再简化:

L2=[s.lower() for s in L1 if isinstance(s, str)]

这样写会打印不出来非字符串的。楼上if,else那位是正解。


  • 1

Reply