4 python内置函数

1、内置函数的整体介绍

 内置参数官方详解 https://docs.python.org/3/library/functions.html?highlight=built#ascii

2、各内置函数介绍

2.1、map()

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的 

map(function, iterable, ...)

参数

  • function -- 函数,有两个参数
  • iterable -- 一个或多个序列

返回值

Python 2.x 返回列表。

Python 3.x 返回迭代器

Python3 要显示成列表,再前面加list

运行结果:<map object at 0x0000000001E76A90>
原因:在python3中,map() 生成的是迭代器不是list, 你可以在map前加上list,即list(map())


>>>def square(x) : # 计算平方数 ... return x ** 2 ... >>> list(map(square, [1,2,3,4,5])) # 计算列表各个元素的平方 [1, 4, 9, 16, 25] >>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # 使用 lambda 匿名函数 [1, 4, 9, 16, 25] # 提供了两个列表,对相同位置的列表数据进行相加 >>> list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])) [3, 7, 11, 15, 19]

2.2、zip函数

zip函数接受任意多个可迭代对象作为参数,将对象中对应的元素打包成一个tuple,然后返回一个可迭代的zip对象.

这个可迭代对象可以使用循环的方式列出其元素

若多个可迭代对象的长度不一致,则所返回的列表与长度最短的可迭代对象相同.

我们可以使用 list() 转换来输出列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 2.x zip() 返回的是一个列表。

如果需要了解 Pyhton2 的应用

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
 
>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,*zip 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>

 2.3、print()函数

Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

可选关键字参数:
  file:类文件对象(stream); 默认为当前的sys.stdout。
  sep:在值之间插入的字符串,默认为空格。
  end:在最后一个值后附加的字符串,默认为换行符。
  flush:是否强制刷新流。
print('111','222',sep=',')
输出:111,222
msg = '又回到最初的起点'
f = open('print_tofile','w',encoding='utf-8')
print(msg,'记忆中你青涩的脸',sep='|',end='',file=f)

写入到文件:又回到最初的起点|记忆中你青涩的脸
print(msg,'记忆中你青涩的脸',sep='|',end='')
输出到屏幕:又回到最初的起点|记忆中你青涩的脸
 
原文地址:https://www.cnblogs.com/foremostxl/p/9466379.html