Discuss / Python / 有一个疑问

有一个疑问

Topic source

测试例程为: if L2 == ['hello', 'world', 'apple']: print('测试通过!') 此处由 [s.lower() for s in L if isinstance(s,str)] 创建的新list只取L1中的字符串类型元素,由于18不是字符串所以被忽略没有出现在L2中 如果要求同时保留其中的整数类型元素,有什么简便的方法?

大洋芋D

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

我也想过,单纯的用一个列表生成式感觉有点难实现

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

人人仁勇

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

[s.lower() if isinstance(s, str) else s for s in L] 该如何理解,为什么有这种写法?

if instrance(s,str)如果是字符串,真,执行s.lower(),其他执行s,即保留。 if s.isalpha() ,s.isalnum,s.is_integer()是否字符,数字加字符,数字 一样实现

这个是内联if

看到上面说怎么样保留数字,想出了一个比较笨的方法: L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s,str)] for s in L1: if isinstance(s,int)==True: q = L1.index(s) a = len(L1[:q]) L2.insert(a,s) print(L2)

我是新手,欢迎各位大神们指点

明达Colin

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

保留数字18,如果直接添加语句 if isinstance(s.int) == true: L2.append(s.lower()) 报错类型是s.lower()没有定义 求大神告知怎么解决?

明达Colin

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

打错了应该是 if isinstance(s,int) == true:


  • 1

Reply