源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python基础学习之常见的内建函数整理

  • 时间:2022-04-03 09:05 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python基础学习之常见的内建函数整理
[b] 前言[/b] Python针对众多的类型,提供了众多的内建函数来处理,这些内建函数功用在于其往往可对多种类型对象进行类似的操作,即多种类型对象的共有的操作,下面话不多说了,来一看看详细的介绍吧。 [b]map()[/b] map()函数接受两个参数,一个是函数,一个是可迭代对象(Iterable),map将传入的函数依次作用到可迭代对象的每一个元素,并把结果作为迭代器(Iterator)返回。 举例说明,有一个函数[code]f(x)=x^2 [/code],要把这个函数作用到一个[code]list[1,2,3,4,5,6,7,8,9][/code]上: 运用简单的循环可以实现:
>>> def f(x):
...  return x * x
...
L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
 L.append(f(n))
print(L)
运用高阶函数[code]map()[/code] :
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
结果r是一个迭代器,迭代器是惰性序列,通过[code]list()[/code]函数让它把整个序列都计算出来并返回一个list。 如果要把这个list所有数字转为字符串利用[code]map()[/code]就简单了:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
[b]小练习:[/b]利用[code]map()[/code]函数,把用户输入的不规范的英文名字变为首字母大写其他小写的规范名字。输入[code]['adam', 'LISA', 'barT'],[/code]输出[code]['Adam', 'Lisa', 'Bart'][/code]
def normalize(name):
  return name.capitalize()

 l1=["adam","LISA","barT"]
 l2=list(map(normalize,l1))
 print(l2)
[b]reduce()[/b] [code]reduce()[/code]函数也是接受两个参数,一个是函数,一个是可迭代对象,reduce将传入的函数作用到可迭代对象的每个元素的结果做累计计算。然后将最终结果返回。 效果就是:[code]reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)[/code] 举例说明,将序列[code][1,2,3,4,5][/code]变换成整数12345:
>>> from functools import reduce
>>> def fn(x, y):
...  return x * 10 + y
...
>>> reduce(fn, [1, 2, 3, 4, 5])
12345
小练习:编写一个[code]prod()[/code]函数,可以接受一个list并利用reduce求积:
from functools import reduce
def pro (x,y):
  return x * y
 def prod(L):
  return reduce(pro,L)
 print(prod([1,3,5,7]))
[code]map()[/code]和[code]reduce()[/code]综合练习:编写str2float函数,把字符串'123.456'转换成浮点型123.456
CHAR_TO_FLOAT = {
 '0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9, '.': -1
}
def str2float(s):
 nums = map(lambda ch:CHAR_TO_FLOAT[ch],s)
 point = 0
 def to_float(f,n):
   nonlocal point
   if n==-1:
    point =1
    return f
   if point ==0:
    return f*10+n
   else:
    point =point *10
    return f + n/point

 return reduce(to_float,nums,0)#第三个参数0是初始值,对应to_float中f
[b]filter()[/b] [code]filter()[/code]函数用于过滤序列,[code]filter()[/code]也接受一个函数和一个序列,[code]filter()[/code]把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 举例说明,删除list中的偶数:
def is_odd(n):
 return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
[b]小练习:用filter()求素数[/b] 计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单: 首先,列出从2开始的所有自然数,构造一个序列: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... 取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉: 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... 取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉: 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... 取新序列的第一个数5,然后用5把序列的5的倍数筛掉: 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... 不断筛下去,就可以得到所有的素数。 用Python实现这个算法,先构造一个从3开始的期数数列:
def _odd_iter(): 
n = 1
 while True:
  n = n + 2
  yield n
#这是一个生成器,并且是一个无线序列
定义一个筛选函数:
def _not_divisible(n):
 return lambda x: x % n > 0
定义一个生成器不断返回下一个素数:
def primes():
 yield 2
 it = _odd_iter() # 初始序列
 while True:
  n = next(it) # 返回序列的第一个数
  yield n
  it = filter(_not_divisible(n), it) # 构造新序列
打印100以内素数:
for n in primes():
 if n < 100:
  print(n)
 else:
  break
[b]sorted()[/b] python内置的[code]sorted()[/code]函数可以对list进行排序:
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
[code]sorted()[/code]函数也是一个高阶函数,还可以接受一个key函数来实现自定义排序:
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序. 默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。如果想忽略大小写可都转换成小写来比较:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
要进行反向排序,不必改动key函数,可以传入第三个参数[code]reverse=True[/code]:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
[b]小练习:[/b]假设我们用一组tuple表示学生名字和成绩:[code]L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] [/code]。用[code]sorted()[/code]对上述列表分别按c成绩从高到低排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_score(t):
 for i in t:
   return t[1]
L2=sorted(L,key= by_score)
print(L2)
运用匿名函数更简洁:
L2=sorted(L,key=lambda t:t[1])
print(L2)
[b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部