Discuss / Python / 关于最后小测题的一个拓展疑问

关于最后小测题的一个拓展疑问

Topic source

ShawnUF

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

后面的小测题如果希望数组L1中字符串元素变成小写,但其他类型元素原样保留该怎么做呢?列表表达式可以做到么?

L1 = ['Hello', 'World', 18, 'Apple', None]

L2 = ???

期待输出: L2 = ['hello', 'world', 18, 'apple', None]

何明远1993

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

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

zmy235

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

@何明远1993,这个输出跟题意不符合,题目要求只输出字符串,忽略非字符串

ShawnUF

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

@何明远1993 受教了

from functools import partial
L2 = [n.lower() for n in list(filter(partial(isinstance, class_or_tuple=str),L1))]

写这个答案的人好明显没有测试过代码: L2 = [s.lower() for s in L1 if isinstance(s,str) ] L1里面有个None元素,可定会有以下错误: TypeError: isinstance() arg 2 must be a type or tuple of types isinstance()第一个参数如果是None就抛错了。 针对L1的正确答案应该是: L2 = [x.lower() for x in L1 if not isinstance(x,(type(None),int)) ] 如果L1还有其他类型的元素暂时只能在第二个参数加上,我暂时想不出只筛选字符串类型的写法,如果有更好的写法请指教!

何明远1993

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

@Eason仔宵夜達

试了python3.5.2, python3.6.0, python2.7.12, python2.6.6 四个版本的python,isinstance函数可以直接判断None类型。 没有更低版本的python了就没有继续测试

>>> isinstance(None,str)
False
>>>

从你发出来的报错信息看,是isinstance函数的第二个参数的问题,应该和None类型无关

你是把 isinstance(s,str)写成 isinstance(s,str())了吧


  • 1

Reply