python 内置函数一览

int(x, base=10) 将一个字符串或数字转换为整型, 默认十进制
>>> int('120')
120
>>> int(120.12)
120
>>> int('10', base=16)
16
str() 将对象转化为适于人阅读的形式,即字符串
# 数字转中文
>>> str(100)
'100'
# unicode 转中文
>>> str('\u6d4b\u8bd5')
'测试'
dict() 初始化一个字典
>>> dict()
{}
>>> dict(a=1,b=2)
{'a': 1, 'b': 2}
list([iterable]) 初始化一个列表
>>> list()
[]
>>> list(range(5))
[0, 1, 2, 3, 4]
tuple([iterable]) 初始化一个元祖
>>> tuple()
()
>>> tuple(range(1))
(0,)
set([iterable]) 初始化一个集合(无序不重复)

关于set的操作可以参考 https://blog.csdn.net/youzi_yun/article/details/101554342

>>> set()
set()
>>> set([1,2,3,2,4])
{1, 2, 3, 4}
abs() 返回数字的绝对值
>>> abs(-1)
1
>>> abs(1)
1
divmod() 把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)
>>> divmod(7,3)
(2, 1)
>>> divmod(10,2)
(5, 0)
>>> 
input() 获取控制台的输入
>>> a = input("input:")
input:test
>>> a
'test'
open(name[, mode[, buffering]]) 打开一个文件,创建一个 file 对象, 一般结合上下文管理器 with 使用
>>> with open('test.txt', 'r') as f:
...     print(f.readline())
... 
hello world!
staticmethod() 静态方法

用作定义类里的静态方法,静态方法中不需要额外定义参数,因此在静态方法中引用类属性的话,必须通过类对象来引用。

class A:
   @staticmethod
   def test():
        print('test-----')

调用方式:A.test()
all(iterable) 如果给定的可迭代对象 中的所有元素都为 TRUE则返回 True,否则返回 False。
>>> all([1,2,3,4])
True
>>> all([0,1,2])
False
any(iterable) 如果给定的可迭代对象 中的所有元素至少有一个为 True 则返回 True,所有元素都为False则返回 False。
>>> all([1,2,3,4])
True
>>> all([0,1,2])
True
>>> all([0,'',False])
Flase
enumerate(iterable, [start=0]) 在可迭代对象中添加一个索引序列,一般用在 for 循环当中。

Python 2.3. 以上版本可用,2.6 添加 start 参数。

>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three
ascii 将传入的对象转为 ASCII 表达式
>>> ascii('测试')
"'\\u6d4b\\u8bd5'"
>>> str('\u6d4b\u8bd5')
'测试'
bin 返回整数的二进制表达式
>>> bin(1)
'0b1'
>>> bin(8)
'0b1000'
>>> 
callable 判断一个对象是否是可调用的(是否实现了__call__方法)
>>> callable(1)
False
>>> callable(str)
True
chr 返回一个整数的Unicode 字符串
>>> chr(1)
'\x01'
>>> chr(10)
'\n'
>>> chr(15)
'\x0f'
compile(source, filename, mode[, flags[, dont_inherit]]) 编译一段源码使其可以被exec() 或 eval() 调用
参数
source -- 字符串或者AST(Abstract Syntax Trees)对象。。
filename -- 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
mode -- 指定编译代码的种类。可以指定为 exec, eval, single。
flags -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。。
flags和dont_inherit是用来控制编译源码时的标志

>>> a = compile('print(2*3)','', 'eval')
>>> eval(a)
6
>>> a = compile('print(2*3)','', 'exec')
>>> exec(a)
6
eval 执行一个字符串表达式,并返回表达式的值。
>>> eval('print(5*5)')
25
>>> eval('8+2')
10

# 还能返回表达式的原始类型
>>> ret = eval("{'a':1}")
>>> type(ret)
<class 'dict'>
>>> ret
{'a': 1}
exec 作用同eval,不同的是,exec 可以执行一个代码块,eval只能执行一个表达式
>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax
delattr(obj, attribute_name) 从给定对象中删除指定属性, 传入参数为 对象,属性的字符串名称
>>> class A:
...     a = 1
...     b = 2
... 
>>> print(A.a)
1
>>> delattr(A, 'a')
>>> print(A.a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'A' has no attribute 'a'
>>> print(A.b)
2
format 返回 value.format(format_spec)

通常用于格式化字符串

>>> '{}今年5岁了'.format('小明')
'小明今年5岁了'
getattr(object, name, default=None) 返回一个对象的属性,getattr(x, ‘y’) 等同于 x.y,属性不存在的时候返回default值
>>> getattr(int, '__add__')
<slot wrapper '__add__' of 'int' objects>
>>> getattr(int, '__sum__')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'int' has no attribute '__sum__'
globals 以dict的形式返回当前环境中的全局变量
>>> globals()
{'__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__package__': None}
>>> a = 'test'
>>> globals()
{'__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 'test', '__package__': None}
hasattr 判断对象是否有某个属性

通过 getattr 实现,若捕获AttributeError则返回False,否则返回True

>>> hasattr(int,'__add__')
True
>>> hasattr(int,'__sum__')
False
hash 返回一个对象的哈希值,若判断两个对象相等,那他们的哈希值必然相等,但是倒序这个对象,哈希值不一定相等
>>> hash('abc')
4697863510219724172
>>> a = 'abc'
>>> hash(a)
4697863510219724172
help 通过help 会展示出对象的所有属性, 是对 pydoc.help 的封装
>>> help(int)
hex 返回一个整数的16进制表达式
>>> hex(16)
'0x10'
>>> hex(10)
'0xa'
>>> hex(18)
'0x12'
id CPython解释器返回的是对象的内存地址, 可以很靠谱的来判断已存在的对象是否一致
>>> id(1)
4305218368
isinstance 用于判断一个类的实例是否是它的子类
>>> isinstance((1,2), tuple)
True
>>> isinstance((1,2), list)
False
issubclass 判断一个类是否是另一个类的子类或相同类 issubclass(x, (A, B, …)) 等同于 issubclass(x, A) or issubclass(x, B) or …
>>> issubclass(dict, dict)
True
>>> issubclass(dict, (int, dict))
True
iter 传入一个可迭代对象,返回一个迭代器
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

>>> iter([1,2])
<list_iterator object at 0x1044b10f0>
len 返回一个容器中元素的数量,比如list, dict 等
>>> len(range(2,5))
3
locals 以dict的形式返回当前环境中的局部变量
max 返回最大值, 若可迭代对象是空,则返回default值
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value

>>> max(1,5,2,7)
7
>>> max([],default=10)
10
min 返回最小值, 若可迭代对象是空,则返回default值
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value

>>> min([],default=10)
10
>>> min(1,5,2,7)
1
next(iterator[, default]) 返回可迭代对象的下个元素,若设置了default值,则在迭代器耗尽的时候返回default值,否则抛出StopIteration异常
>>> a = iter([1,2,3])
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>> a = iter([1,2,3])
>>> next(a, 9)
1
>>> next(a, 9)
2
>>> next(a, 9)
3
>>> next(a, 9)
9
oct 返回一个整数的八进制
>>> oct(1)
'0o1'
>>> oct(8)
'0o10'
>>> oct(9)
'0o11'
ord 返回一个字符串长度的 Unicode 编码

ord() 是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

>>> ord('1')
49
>>> ord('15')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
pow 若传入两个参数,等同于xy;若传入三个参数,等同于xy % z
>>> pow(2,3)
8
>>> pow(2,3,5)
3
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) 用于打印输出

print 在 Python3.x 是一个函数,但在 Python2.x 版本不是一个函数,只是一个关键字。

参数
objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
sep -- 用来间隔多个对象,默认值是一个空格。
end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
file -- 要写入的文件对象。

>>> print('test')
test
>>> print('test', 1,2)
test 1 2
repr 将对象转化为供解释器读取的形式
>>> repr(1)
'1'
>>> repr({'a':1})
"{'a': 1}"
round 返回浮点数x的四舍五入值

ndigits 可能是负数

>>> round(1.23)
1
>>> round(1.73)
2
>>> round(-1.73)
-2
>>> round(-1.13)
-1
>>> round(-0.9)
-1
setattr(object, name, value) 为一个对象设置属性,可以对已存在的属性进行赋值或新增属性

setattr(x, ‘y’, v) 和 x.y = v 等价

>>>class A():
...     name = "小明"
... 
>>> a = A()
>>> setattr(a, "age", 5)
>>> print(a.age)
5
sorted(iterable, key=None, reverse=False) 返回可迭代的对象的排序列表

sort 与 sorted 区别:

  • sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
    list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值.
  • 内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
参数说明:
iterable -- 可迭代对象。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

# sort 原来的列表发生了变化
>>> a = [5,4,3]
>>> a.sort()
>>> a
[3, 4, 5]

# sort 原来的列表不变
>>> a = [5,4,3]
>>> sorted(a)
[3, 4, 5]
>>> a
[5, 4, 3]

# 利用key
>>> sorted([('b', 2), ('d', 4),('a', 1),('c', 3)],key=lambda x:x[1])
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
sum 返回可迭代对象中的数字的总和, 默认为从0开始加
>>> sum([1,2,3])
6
>>> sum([])
0
vars(p_object=None) 返回对象object的属性和属性值的字典对象。 不带参数等同于locals(), 带参数等同于object.dict.
>>> vars()
{'__name__': '__main__', '__spec__': None, '__doc__': None, 'a': [5, 4, 3], '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

>>> vars(dict)
mappingproxy({'__contains__': <method '__contains__' of 'dict' objects>, '__ge__': <slot wrapper '__ge__' of 'dict' objects>, '__init__': <slot wrapper '__init__' of 'dict' objects>, 'fromkeys': <method 'fromkeys' of 'dict' objects>, '__len__': <slot wrapper '__len__' of 'dict' objects>, '__doc__': "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n    (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n    d = {}\n    for k, v in iterable:\n        d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n    in the keyword argument list.  For example:  dict(one=1, two=2)", '__sizeof__': <method '__sizeof__' of 'dict' objects>, 'copy': <method 'copy' of 'dict' objects>, '__lt__': <slot wrapper '__lt__' of 'dict' objects>, 'update': <method 'update' of 'dict' objects>, 'pop': <method 'pop' of 'dict' objects>, '__eq__': <slot wrapper '__eq__' of 'dict' objects>, '__le__': <slot wrapper '__le__' of 'dict' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'dict' objects>, '__iter__': <slot wrapper '__iter__' of 'dict' objects>, 'popitem': <method 'popitem' of 'dict' objects>, 'items': <method 'items' of 'dict' objects>, '__gt__': <slot wrapper '__gt__' of 'dict' objects>, '__hash__': None, 'clear': <method 'clear' of 'dict' objects>, 'get': <method 'get' of 'dict' objects>, '__repr__': <slot wrapper '__repr__' of 'dict' objects>, '__ne__': <slot wrapper '__ne__' of 'dict' objects>, 'setdefault': <method 'setdefault' of 'dict' objects>, '__new__': <built-in method __new__ of type object at 0x100976960>, '__setitem__': <slot wrapper '__setitem__' of 'dict' objects>, 'keys': <method 'keys' of 'dict' objects>, '__getitem__': <method '__getitem__' of 'dict' objects>, '__delitem__': <slot wrapper '__delitem__' of 'dict' objects>, 'values': <method 'values' of 'dict' objects>})
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值