Discuss / Python / 练习

练习

Topic source

無淣

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

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)==True else s for s in L1]

print(L2)

print(L3)

Mr.Wang

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

L3=[s.lower() if isinstance(s,str)==True else s for s in L1]

===>

['hello', 'world', 18, 'apple', None]

为什么你这样转一下就可以了?'else s'自动把s转成字符串了?有点不理解

print([name.lower() if isinstance(name, str) else str(name) for name in L])

===>

['hello', 'world', '18', 'apple', 'None']

这样才是转成字符串呀

刘生

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

没有转换为字符,意思是如果list中的元素不是字符串,那么元素的数据类型不变。


  • 1

Reply