python常用函数
split() 函数
split()函数的用法示例。
- 获取一个当前路径的字符串
- 然后使用split()函数拆分成为一个新的数组
- 之后使用filter函数剔除空字符串
- 最后循环遍历
import os
path = os.getcwd()
#'/home/testuser2022/django_projects'
tmp_list = path.split('/')
#['', 'home', 'testuser2022', 'django_projects']
a_list = filter(lambda x: x in tmp_list and len(x) >0, iter(tmp_list))
#使用next(), 注意处理StopIteration
while True:
try:
print(next(a_list))
except StopIteration:
break
#生成一个list
b_list = list(a_list)
#['home', 'testuser2022', 'django_projects']
注意
- 使用filter过滤函数的时候,原型是filter(function, iterator),第一个参数我们传入的是lambda, 它的第一个参数是自命名的,这里使用x, 当然也可以使用其他的自命名变量来作为参数, 当然可以使用tuple等其他的形式。
- lambda x: x in set and if condition, 注意可以使用and 或者or 来进行逻辑条件限定。
- 返回值是iterator,所以使用next()来获得值并且指向下一个值,当然最后要处理指向空值的情况,即处理StopIteration
- 直接的处理方法,可以使用list()或者其他构造函数,来构造一个新的容器,这里使用的是list(),当然可以使用set()或者map()