Discuss / Python / 求解怎么将非字符串不变成字符串保存在新list里呢?

求解怎么将非字符串不变成字符串保存在新list里呢?

Topic source

求助大神... 输出结果是L2 = ['hello', 'world', 18, 'apple', None],只有字符串变。

信勒个达

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

可以把isinstance判断True的结果放在一个列表里,False的放在一个列表里,然后合并

信勒个达

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

比如这样 L3 = [] for l in L: if isinstance(l,str): L3.append(l.lower()) else: L3.append(l) print(L3)

谢谢,如果写成列表生成式该咋写呢?

l2=[j for j in l1 if not isinstance(j,str)] 直接在 if 后面加一个 not 就表示判断为 false 的值

[x.lower() for x in L1 if isinstance(x,str)] + [x for x in L1 if not isinstance(x,str)]

好的,谢谢~

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


  • 1

Reply