美文网首页
python基础之常用函数

python基础之常用函数

作者: JNChenFeng | 来源:发表于2018-07-08 23:33 被阅读0次

filter

功能:对数组进行做过滤,函数接收一个函数 f 和一个list

  • 如果从一个数组中需要过滤出所有的偶数
ss = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = filter(lambda x: x % 2 == 0, ss)
  • 从字符串中提取数字
s = '123456adafdsa789'
number_str = filter(str.isdigit,s)

enumerate

函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

  • 遍历数组时得到数组下标和值
# 不推荐写法
i = 0
l = [1,2,3,4,5,6,7,8,9]
for temp in l:
    print(i,temp)
    i += 1
# 推荐写法 使用enumerate
l = [1,2,3,4,5,6,7,8,9]
for index,value in enumerate(l):
    print(index,value)

map

map() 会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表

  • 比如我们需要查一批学生的信息,查询的方法定义为 query_student_info(user_id)
# 不推荐写法
user_id_list = [1,2,3]
user_info_list = []
for user_id in user_id_list:
    user_info_list.append(query_student_info(user_id))
# 推荐写法,map在一定程度上可以减少for循环的使用
user_id_list = [1,2,3]
user_info_list = list(map(query_student_info,user_id_list))

reverse

反转列表

l = [1,2,3]
print(l.reverse()) # 输出数组 3,2,1

zip

压缩可迭代对象

  • 生成字典
k = ['name','age','sex']
v = ['chen','1','f']
l = list(zip(k,v))
temp_dict = dict(l) # {'age': '1', 'name': 'chen', 'sex': 'f'}

rang

创建一个整数列表,range(start, stop[, step]),生成的列表左闭右开,主要使用在for循环中,

print(rang(1,9)) # [1, 2, 3, 4, 5, 6, 7, 8]

相关文章

网友评论

      本文标题:python基础之常用函数

      本文链接:https://www.haomeiwen.com/subject/yguauftx.html