封装函数将列表的字符串变小写(不需要用列表推导式)
时间: 2024-03-26 15:42:09 浏览: 55
好的,以下是一个不使用列表推导式的函数,它将列表中的字符串转换为小写。
```python
def lowercase_list(lst):
"""
将列表中的字符串全部转换为小写字母
:param lst: 待处理的列表
:return: 转换后的新列表
"""
result = []
for item in lst:
if isinstance(item, str):
result.append(item.lower())
else:
result.append(item)
return result
```
这个函数使用了一个简单的 for 循环遍历列表,并使用 isinstance() 函数检查每个元素是否为字符串。如果是字符串,就将其转换为小写,并将其添加到一个新的结果列表中。如果不是字符串,则直接将其添加到结果列表中。
运行示例:
```python
my_list = ['AbC', 'DeF', 123, 'GhI']
new_list = lowercase_list(my_list)
print(new_list)
```
输出结果为:
```
['abc', 'def', 123, 'ghi']
```
请注意,这个函数不会删除列表中的非字符串元素,而是将它们原样返回。
阅读全文
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)