190715 Python 内置函数之frozenset

返回一个固定的集合,不允许添加or删除、修改集合

1
>>> a = frozenset(range(10))

190715 Python 内置函数之format

字符串格式化函数 str.format()

1
2
3
4
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{0} {1} {0}".format("hello", "world")
'hello world hello'

除了使用上面序号的方式,还可以用key的方式,如下

1
2
3
4
5
>>> "{name} haha {age}".format(name='yhh', age=20)
'yhh haha 20'

>>> "{name} haha {age}".format(**{"name": "yhh", "age": 18})
'yhh haha 20'

注意,传参为dict时,前面要加两个星号

数字格式化

1
2
>>> "{:.2f}".format(3.1415926)
'3.14'

190715 Python 内置函数之float

将整数和字符串转换成浮点数

1
2
3
4
>>> float(1)
1.0
>>> float('12')
12.0

190715 Python 内置函数之filter

用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换

1
filter(function, iterable)
  • function: 过滤函数
  • iterable: 序列

实例如下

1
2
3
4
5
>>> def f(s):
... return s % 2 == 0
...
>>> a = filter(f, [1,2,3,4])
>>> list(a)

190715 Python 内置函数之exec

执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码

举例如下:

1
2
3
4
5
6
>>> exec('print("Hello World")')
Hello World
>>> exec('for i in range(0,3): print(i)')
0
1
2

进阶

exec除了接收上面的python语句块之外,还可以接收表示全局和局部命名空间的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> x = 10
>>> expr = """
... z = 30
... sum = x + y + z
... print(sum)
... """
>>>
>>> def func():
... y = 20
... exec(expr)
... exec(expr, {'x': 1, 'y': 2})
... exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
...
>>> func()
60
33
34

190715 Python 内置函数之delattr

顾名思义,这个使用来删除属性的

delattr(x, 'foobar') 相等于 del x.foobar

举例说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A:
... x = 10
... y = 10
... z = 20


>>> delattr(A, 'z')
>>> a = A()
>>> a.x
10
>>> a.z
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'z'

不太知道什么场景会用这个

190715 Python 内置函数之eval

主要用来执行字符串表达式,和 compile有一些区别,后者功能更加强大,可以编译字符串格式的python代码,而eval更多的是基础运算

举例如下:

1
2
3
4
5
6
7
8
>>> a = 10
>>> eval('a + 10')
20
>>> eval('pow(a,2)')
100
>>> b = [1,2]
>>> eval('b[1]')
2

请注意,eval对表达式有限定,如果需要更丰富的支持,可以考虑exec

190715 Python 内置函数之complex

数学中的复数,通过complex可以简单的生成

1
2
3
4
>>> complex(1, 2)
(1+2j)
>>> complex("1+2j")
(1+2j)

注意,字符串转换时,加号左右两边不能有空格

190715 Python 内置函数之enumerate

将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标

一个常见的使用case

1
2
3
4
5
6
7
>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print(i, element)
...
0 one
1 two
2 three

190715 Python 内置函数之divmod

接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b)

1
2
>>> divmod(10, 3)
(3, 1)

190715 Python 内置函数之dir

不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表

语法

1
dir([object])

实例

1
2
3
4
5
6
7
8
>>> class A:
... x = 10
... def m():
... print('haha')
...
>>> a = A()
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm', 'x']

190715 Python 内置函数之dict

dict用于创建字典

1
2
3
4
5
6
>>> dict()
{}
>>> dict(a='a', b='b', c='c')
{'a': 'a', 'b': 'b', 'c': 'c'}
>>> dict([(1,10), (2, 20), (3,30)])
{1: 10, 2: 20, 3: 30}

请注意,传参为可迭代的序列的场景

190715 Python 内置函数之compile

将一个字符串编译为字节代码

这个比较厉害了,传入一段字符串,把它编译成可执行的脚本

语法

1
compile(source, filename, mode[, flags[, dont_inherit]])
  • source – 字符串或者AST(Abstract Syntax Trees)对象。。
  • filename – 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
  • mode – 指定编译代码的种类。可以指定为 exec, eval, single
  • flags – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。。
  • flagsdont_inherit是用来控制编译源码时的标志

举例说明

1
2
3
>>> str = "for i in range(0,10): print(i)"
>>> c = compile(str, '', 'exec')
>>> exec(c)

190715 Python 内置函数之classmethod

修饰符对应的函数不需要实例化,不需要self参数,第一个参数需要是表示自身类的cls参数,可以来调用类的属性,类的方法,实例化对象

举例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> class A:
... a = 10
... def m1(self):
... print("m1")
...
... @classmethod
... def m2(cls):
... print(cls.a)
... # 创建对象,然后再访问方法
... cls().m1()
...
>>> A.m2()
10
m1

190715 Python 内置函数之chr

chr() 参数为整数,返回一个对应的字符

1
2
3
4
5
6
>>> chr(10)
'\n'
>>> chr(78)
'N'
>>> chr(22020)
'嘄'

请注意传参可以为10进制,也可以为16进制,取值为 [0,114111]/[0,0x10FFFF])

190715 Python 内置函数之callable

检查一个对象是否是可调用,对于函数、方法、lambda 函式、 类以及实现了 __call__ 方法的类实例, 它都返回 True

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> callable(10)
False

>>> def a():
... return 1
...
>>> callable(a)
True

>>> class A:
... def m():
... pass
...
>>> callable(A)
True

>>> a = A()
>>> callable(a)
>>> callable(a.m)
True

190715 Python 内置函数之bytes

返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。

基本用法和 bytearray 相似,唯一区别是返回的数组是不可变的

举例如下

1
2
3
4
5
6
7
8
9
10
11
12
>>> bytes([1,2,3])
b'\x01\x02\x03'
>>> bytes('hello', 'utf-8')
b'hello'
>>> bytes(1)
b'\x00'

>>> a = bytes([1,2,3])
>>> a[1] = 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

请注意,数组内容不可变,强制赋值时抛异常

190715 Python 内置函数之bytearray

返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256

语法:

1
class bytearray([source[, encoding[, errors]]])

参数说明:

  • source
    • 为整数,则返回一个长度为source的初始化数组
    • 字符串,则按照指定的 encoding 将字符串转换为字节序列
    • 迭代类型,则元素必须为[0,255]之间的整数
    • 无参数,初始化数组个数为0

实例

1
2
3
4
5
6
7
8
9
10
>>> bytearray('hello', 'utf-8')
bytearray(b'hello')
>>> bytearray(2)
bytearray(b'\x00\x00')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> a = bytearray([1,2,3])
>>> a[1] = 20
>>> a
bytearray(b'\x01\x14\x03')

190715 Python 内置函数之bool

bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。

bool 是 int 的子类。

1
2
3
4
5
6
>>> bool('True')
True
>>> bool('true')
True
>>> bool(2)
True

190715 Python 内置函数之bin

bin() 返回一个整数 int 或者长整数 long int 的二进制表示。

1
2
3
4
>>> bin(10)
'0b1010'
>>> bin(16)
'0b10000'
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×