python3.x 基础二:内置函数
自带的函数可以非常简单快捷的实现某些功能,
比如产生一个序列,可以用循环实现:
count = 0
while count < 10:
print(count)
count+=1
但其实用range会更简单:
for i in range(10):
print(i)
在python命令行下查看帮助:
help() help> str
或者
help(str)
1.abs(x, /)
Return the absolute value of the argument.
- 返回绝对值
>>> print(abs(10))
10
>>> print(abs(-10))
10
>>> print(abs(10.5))
10.5
>>> print(abs(-10.5))
10.5
- 复数,此方法返回此复数的绝对值(此复数与它的共轭复数的乘积的平方根)--基本用不上了,复数在工程领域使用
2.all(iterable, /)
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
- 全部元素为真,则为真,否则为假
>>> all([-1,0,1])
False
3.any(iterable, /)
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
- 一个为真,,则为真,否则为假
>>> any([-1,0,1])
True
4.ascii(obj, /) 同repr()
Return an ASCII-only representation of an object.
- 返回可打印对象的字符串表示
>>> ascii(100)
''
>>> ascii('')
"'100'"
>>> ascii('abcd')
"'abcd'"
>>> ascii('水电费水电费')
"'\\u6c34\\u7535\\u8d39\\u6c34\\u7535\\u8d39'"
5.bin(number, /)
Return the binary representation of an integer.
- 返回整形的二进制
>>> bin(1)
'0b1'
>>> bin(255)
'0b11111111'
6.| bool(x) -> bool
- 返回真假,1为真,0 为假,空为假
7.bytearrayclass bytearray(object)
| bytearray(iterable_of_ints) -> bytearray
| bytearray(string, encoding[, errors]) -> bytearray
| bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
| bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
| bytearray() -> empty bytes array
- 把二进制变成一个可修改的列表
>>> b=bytearray('abcd',encoding='utf-8')
>>> b[0]
97
>>> b
bytearray(b'abcd')
>>> b[1]
98
>>> b[1]='B'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> b[1]=100
>>> b
bytearray(b'adcd')
>>> b[1]=200
>>> b
bytearray(b'a\xc8cd')
8.bytes
class bytes(object)
| bytes(iterable_of_ints) -> bytes
| bytes(string, encoding[, errors]) -> bytes
| bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
| bytes(int) -> bytes object of size given by the parameter initialized with null bytes
| bytes() -> empty bytes object
- 字符串不可修改,做的各种操作都会新开辟一个内存空间
>>> ascii('水电费水电费')
"'\\u6c34\\u7535\\u8d39\\u6c34\\u7535\\u8d39'"
>>> a=bytes('abcd',encoding='utf-8')
>>> print(a.upper(),a)
b'ABCD' b'abcd'
- 不写参数,返回长度为0的字节数组
>>> bytes()
b''
>>> print(bytes())
b''
>>> len(bytes())
0
>>> print(type(len(bytes())))
<class 'int'>
- source为字符串时,必须编码,并使用str.encode()转换成字节数组
>>> bytes('asdf','utf-8')
b'asdf'
>>> bytes('水电费','utf-8')
b'\xe6\xb0\xb4\xe7\x94\xb5\xe8\xb4\xb9'
9.callable(obj, /)
Return whether the object is callable (i.e., some kind of function).
- 返回一个对象是否可调用
>>> def func():
... print('aa')
...
>>> callable(func)
True
10.chr(i, /)
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
- 返回ASCII码对应的字符
>>> chr(97)
'a'
11.ord(c, /)
Return the Unicode code point for a one-character string.
- 返回ASCII值,只能传入1个字符
>>> ord('a')
97
>>> ord('1')
49
>>> ord('A')
65
>>> ord('10000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 5 found
12.compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Compile source into a code object that can be executed by exec() or eval().
- exec(code),远程执行一段代码
code='''
def fib(n):
if n==0:
return 0
elif n ==1 or n ==2:
return 1
return fib(n-1)+fib(n-2)
print(fib(10))
'''
exec(code)
13.class dict(object)
| dict() -> new empty dictionary
- 字典构造函数
14.dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attribut
- 返回一个对象的所有属性列表
15.divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
- 返回被除数的商和余数
>>> divmod(10,3)
(3, 1)
16.eval(source, globals=None, locals=None, /)
Evaluate the given source in the context of globals and locals.
- 返回字符串的运算结果,只能是简单的
>>> eval('1+2*3')
7
17.class filter(object)
| filter(function or None, iterable) --> filter object
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
- 过滤返回迭代器为true的所需要元素
>>> res=filter(lambda n:n>5,range(10))
>>> print(res)
<filter object at 0x7f192a00e240>
>>> for i in res:
... print (i)
...
6
7
8
9
18.class frozenset(object)
| frozenset() -> empty frozenset object
| frozenset(iterable) -> frozenset object
- 将一个集合冻结不可修改
>>> set1=set([1,1,2,2,3,3])
>>> set1
{1, 2, 3}
>>> dir(set1)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>> set2=frozenset(set1)
>>> dir(set2)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
19.globals()
Return the dictionary containing the current scope's global variables.
- 返回当前程序的所有全局变量k/v
20.hash(obj, /)
Return the hash value for the given object.
- 返回哈希值
21.hex(number, /)
Return the hexadecimal representation of an integer.
>>> hex(1)
'0x1'
>>> hex(10)
'0xa'
>>> hex(255)
'0xff'
22.正常数字字符串是可以转换成整型的
- float,返回浮点型
23.isinstance(obj, class_or_tuple, /)
Return whether an object is an instance of a class or of a subclass thereof.
- 判断对象是否是类或者其他实例
- 判断迭代器或者迭代类型
24.iter(...)
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
- 将一个可迭代对象转换为迭代器
25.len(obj, /)
Return the number of items in a container.
- 返回对象的长度(没看明白/表示什么意思)
>>> count_str=len('abcd')
>>> count_tuple=len((1,2,3,4,5))
>>> count_list=len([1,2,3,4,5])
>>> count_dict=len({'a':1,'b':2,'c':3})
>>> count_set=len({1,2,3,4,5})
>>> print(count_str,count_tuple,count_list,count_dict,count_set)
4 5 5 3 5
>>>
- 整型或者浮点型的不可以直接计算长度,否则报错
>>> len(123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(123.1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'float' has no len()
26.class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
|
- 可以返回空列表
- 可以将字符串/元组/range对象转换成列
27.locals()
Return a dictionary containing the current scope's local variables.
- globals
28.class map(object)
| map(func, *iterables) --> map object
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
- 将可迭代类型元素应用到func函数
>>> res=map(lambda x:x*2,range(5))
>>> print(res)
<map object at 0x7f192a00e1d0>
>>> for i in res:
... print(i)
...
0
2
4
6
8
29.max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
- 为数字则返回最大值
- 为字符,则返回ASCII值大者
>>> max(,,,) >>> max('a','b','c')
'c'
>>> max('a','A')
'a'
- min()同理
30.oct(number, /)
Return the octal representation of an integer.
- 将一个整数转换为八进制
>>> oct(1)
'0o1'
>>> oct(8)
'0o10'
>>> oct(9)
'0o11'
31pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
- 求幂
>>> pow(3,3)
27
>>> pow(2,8)
256
32.class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).
range(10)
- 表示0,1,2,3,4,5,6,7,8,9序列,等价于range(0,10)或者range(0,10,1)
- object需要为正整数,为负或者浮点数将不会得到你想要的结果
- 默认增加步长为1,不包括停止位
- 步长为正表示增加,为负表示减少
33.class reversed(object)
| reversed(sequence) -> reverse iterator over values of the sequence
- 将一个序列翻转
>>> for i in reversed(range(10)):
... print(i)
...
9
8
7
6
5
4
3
2
1
34.round(...)
round(number[, ndigits]) -> number
- 1个参数下返回整形
- 带指定小数位数时,四舍五入并返回与源数字一样的的类型
>>> round(1,2)
1
>>> round(1.1111,2)
1.11
>>> round(1.999,2)
2.0
36.sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
>>> a={1:2,2:5,6:1,-1:0}
>>> a
{1: 2, 2: 5, -1: 0, 6: 1}
>>> sorted(a)
[-1, 1, 2, 6]
>>> sorted(a.items)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not iterable
>>> sorted(a.items())
[(-1, 0), (1, 2), (2, 5), (6, 1)]
默认按照key排序
>>> sorted(a.items(),key=lambda i:i[1])
[(-1, 0), (6, 1), (1, 2), (2, 5)]
#指定按照value排序
37.class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
- 将其他数据类型转换成字
- 比如上面的求整型/浮点型长度的时候可以先转换成字符
38.sum(iterable, start=0, /)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
- 求和,条件是可迭代类型对象
39.class type(object)
| type(object_or_name, bases, dict)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
- 返回对象的类型,字典/列表取值可以辅助分析
40.class zip(object)
| zip(iter1 [,iter2 [...]]) --> zip object
|
| Return a zip object whose .__next__() method returns a tuple where
| the i-th element comes from the i-th iterable argument. The .__next__()
| method continues until the shortest iterable in the argument sequence
| is exhausted and then it raises StopIteration.
- 返回一个元组
>>> list1=['a','b','c','d','e','f']
>>> list2=[1,2,3,4]
>>> zip(list1,list2)
<zip object at 0x7f1927411ac8>
>>> print(zip(list1,list2))
<zip object at 0x7f19276a1548>>>> for i in zip (list1,list2):
... print(i)
...
('a', 1)
('b', 2)
('c', 3)
('d', 4)
>>>
41.reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
- function 必须是二元函数,在省略第三个参数的情况下,函数先对 iterable 中的第1,2个数据进行操作,得到的结果再与第三个数据用 function() 函数运算……依次类推,最后得到一个结果。如果初始值 initializer 给定,第一次调用会是 initializer 和第一个元素而不是序列的头两个元素。
>>> functools.reduce(lambda x,y:x+y,range(1,5))
10
>>> functools.reduce(lambda x,y: x+y, [1,2,3,4,5], 10)
25
参考link:http://blog.csdn.net/lisonglisonglisong/article/details/38960341
>>> res=map(lambda x:x*2,range(5))
>>> print(res)
<map object at 0x7f192a00e1d0>
>>> for i in res:
... print(i)
...
0
2
4
6
8
python3.x 基础二:内置函数的更多相关文章
- 自学Python3.3-函数分类(内置函数补充)
自学Python之路-Python基础+模块+面向对象自学Python之路-Python网络编程自学Python之路-Python并发编程+数据库+前端自学Python之路-django 自学Pyth ...
- 十六. Python基础(16)--内置函数-2
十六. Python基础(16)--内置函数-2 1 ● 内置函数format() Convert a value to a "formatted" representation. ...
- 十五. Python基础(15)--内置函数-1
十五. Python基础(15)--内置函数-1 1 ● eval(), exec(), compile() 执行字符串数据类型的python代码 检测#import os 'import' in c ...
- python基础(内置函数+文件操作+lambda)
一.内置函数 注:查看详细猛击这里 常用内置函数代码说明: # abs绝对值 # i = abs(-123) # print(i) #返回123,绝对值 # #all,循环参数,如果每个元素为真,那么 ...
- python3全栈开发-内置函数补充,反射,元类,__str__,__del__,exec,type,__call__方法
一.内置函数补充 1.isinstance(obj,cls)检查是否obj是否是类 cls 的对象 class Foo(object): pass obj = Foo() print(isinstan ...
- Python开发基础-Day11内置函数补充、匿名函数、递归函数
内置函数补充 python divmod()函数:把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b) 语法: divmod(a, b) #a.b为数字,a为除数,b ...
- python基础===python内置函数大全
python python内建函数 一.数学运算类 abs(x) 求绝对值1.参数可以是整型,也可以是复数2.若参数是复数,则返回复数的模 complex([real[, imag]]) 创建一个复数 ...
- 第六篇:python基础_6 内置函数与常用模块(一)
本篇内容 内置函数 匿名函数 re模块 time模块 random模块 os模块 sys模块 json与pickle模块 shelve模块 一. 内置函数 1.定义 内置函数又被称为工厂函数. 2.常 ...
- python基础(15):内置函数(一)
1. 内置函数 什么是内置函数? 就是python给你提供的,拿来直接⽤的函数,比如print,input等等,截⽌到python版本3.6.2 python⼀共提供了68个内置函数.他们就是pyth ...
- python3 第三十章 - 内置函数之Dictionary相关
Python字典包含了以下内置函数: 序号 函数及描述 实例 1 len(dict)计算字典元素个数,即键的总数. >>> dict = {'Name': 'cnblogs', 'A ...
随机推荐
- Metasploit渗透测试环境搭建
渗透测试实验环境搭建 下载虚拟机镜像 5个虚拟机镜像,其中Linux攻击机我选择用最新的kali Linux镜像,其余的均使用本书配套的镜像. 网络环境配置 VMware虚拟网络编辑器配置: 将VMn ...
- 一些软件的 Basic Auth 行为
一个 WBEM 在2003年的bug I'm trying to access the WBEM service of the CIMOM on the ESX Server 3i and all m ...
- Add text to 'Ready Page' in Inno Setup
https://stackoverflow.com/questions/1218411/add-text-to-ready-page-in-inno-setup
- Scala教程之:Option-Some-None
文章目录 Option和Some Option和None Option和模式匹配 在java 8中,为了避免NullPointerException,引入了Option,在Scala中也有同样的用法. ...
- Python2 和 Python3的区别
Python2 和 Python3的区别: 1.python2的默认编码方式是ascii码:python3的默认编码是utf-8. 如果出现乱码或者编码错误,可以使用以下编码在文件头来指定编码: #- ...
- mac OS 安装淘宝npm镜像
淘宝npm镜像官网 https://npm.taobao.org/ 在终端输入 npm install -g cnpm --registry=https://registry.npm.taobao.o ...
- L3.二.return
# 函数的返回值 def get_max(a,b,c): max_num=a if b > max_num: max_num = b if c > max_num: max_num = c ...
- 在 AutoLayout 和 Masonry 中使用动画
动画是 iOS 中非常重要的一部分,它给用户展现出应用灵气的一面. 在动画块中修改 Frame 在原来使用 frame 布局时,在 UIView 的 animate block 中对 view 的布局 ...
- Nginx访问日志.Nginx日志切割
11月27日任务 12.10 Nginx访问日志12.11 Nginx日志切割12.12 静态文件不记录日志和过期时间 1.Nginx访问日志 示例一: 日志格式 vim /usr/local/ngi ...
- NodeJS反向代理websocket
如需转载请标明出处:http://blog.csdn.net/itas109QQ技术交流群:129518033 文章目录NodeJS反向代理websocket@[toc]前言代码相关问题:1.http ...