Discuss / Python / 用列表生成式将list中所有字符串改变大小写

用列表生成式将list中所有字符串改变大小写

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

L2 = [s.lower() for s in L1 if isinstance(s, str)]
print(L2)  # 期待输出: ['hello', 'world', 'apple']

L3 = [(s.upper() if isinstance(s, str) else s) for s in L1]
print(L3)  # 期待输出: ['HELLO', 'WORLD', 18, 'APPLE', None]

只改变list中字符串元素,其他元素不变方法copy自楼下评论


  • 1

Reply