python中各类函数的作用

发布于 2022-05-04  379 次阅读


1:map函数

map函数是python中的一个内置函数,map的意思在这里是映射的意思,会根据提供的函数对指定序列做映射。map函数会返回一个迭代器,如果要转换为列表,可以使用 list() 来转换。

语法:map(function, iterable)

function 指的是 函数,iterable 指的是 序列 。序列里的每一个元素作为函数的参数进行计算和定义,函数返回值会被作为新的元素存储起来。

举个栗子:

也可以使用lambda函数,使代码更简单些:

举第二个栗子:

普通的类型转换:

list_of_strings = ["5", "6", "7", "8", "9", "10"]
result = []
for string in list_of_strings:
    result.append(int(string))
print(result)
运行结果为:[5, 6, 7, 8, 9, 10]

map函数转换:

list_of_strings = ["5", "6", "7", "8", "9", "10"]

# map 转换
result = map(int, list_of_strings)
print(list(result))  # 注意使用list 进行了转换
运行结果为:[5, 6, 7, 8, 9, 10]

2:split函数

以下是对于string类型的split函数的作用,当然不局限于string类型;主要作用就是切割字符串,结果返回由字符串元素组成一个列表。

举栗子:

1:无参数时。(当没有参数的情况下,函数默认会以空格,回车符,空格符等作为分割条件)

a="my name is zhangkang"
b="my\nname\nis\nzhangkang"
c="my\tname\tis\tzhangkang"
 
a=a.split()
b=b.split()
c=c.split()
 
print(a)
print(b)
print(c)

输出

2:有参数时:(函数会以参数为分割条件,把字符串进行分割,得到的每个分割段作为列表的元素返回)

d="my,name,is,zhangkang"
e="my;name;is;zhangkang"
f="my-name-is-zhangkang"
 
d=d.split(",")
e=e.split(";")
f=f.split("-")
 
print(d)
print(e)
print(f)

输出:

3:两个参数的情况下:
a="My,name,is,zhangkang,and,I,am,a,student"
b1=a.split(",",1)
b2=a.split(",",2)
b8=a.split(",",8)
b9=a.split(",",9)
 
print(b1)
print(b2)
print(b8)
print(b9)
第一个参数作为分割标志,第二个参数代表分割几次,分割次数若超过字符串最大可分割次数就不会再分割了(程序不会报错),就如上图的b9.

3:ceil(),floor(),round()函数

前俩函数是包含在python中的math库的,使用前要先import math导进来,而round不需调用math库

这三个函数的主要任务就是截掉小数以后的位数,简单来说就是取整用的。

floor() :把数字变小 (向下取整)

ceil() : 把数字变大。(向上取整)

round()  : 四舍五入。(四舍五入)

举栗子:

import math

sample = 1.52

print ("sample: %f ceil(sample): %f" % (sample,math.ceil(sample))

print ("sample: %f floor(sample): %f" % (sample,math.floor(sample))

print ("sample: %f round(sample): %f" % (sample,round(sample))

结果:

sample = 1.49

print ("sample: %f ceil(sample): %f" % (sample,math.ceil(sample))

print ("sample: %f floor(sample): %f" % (sample,math.floor(sample))

print ("sample: %f round(sample): %f" % (sample,round(sample))

结果:

4:排序函数

sort函数

sort函数:

list.sort(cmp=None,key=None,reverse=False)

对原列表进行排序,完成排序后,原列表变为有序列表。

sorted函数

sorted函数:

sorted(iterable, cmp=None, key=None, reverse=False)

cmp: 可以自定义比较参数。
对原列表进行排序,完成排序后,产生一个新的有序列表。

更多内容见文章:(42条消息) Python中的排序函数_python排序函数_vickyθ的博客-CSDN博客


穿过云层我试着努力向你奔跑