Python基础(十三)—切片、yield、生成器、序列化JSON
in python基础 with 0 comment

Python基础(十三)—切片、yield、生成器、序列化JSON

in python基础 with 0 comment

切片 Slice

切片操作基本表达式:object[start_index:end_index:step]

简单的来说,就是start_index、end_index确定起始两个点及方向(start_index -> end_index),而step则是确定方向和步长。

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

print(list[5:3])  # 默认1表示从左往右取值,start_index=5到end_index=3决定了从左往右取值,矛盾,为空

print(list[1:3:-1])  # -1表示从右往左取值,start_index=1到end_index=3决定了从右往左取值,矛盾,为空
print(list[5:3:-1])  # -1表示从右往左取值,start_index=5(f)到end_index=3(d)决定了从左往右取值,['f', 'e']

print(list[-1:3:1])  # 1表示从左往右取值,start_index=-1(g)在end_index=3(d)的右边,因此方向从右往左取值,矛盾,[]
print(list[1:-3:1])  # 1表示从左往右取值,start_index=1(b)在end_index=-3(e)的左边,因此方向从右往左取值,['b', 'c', 'd']

print(list[-2:-5:-1])  # -1表示从右往左取值,start_index=-2(f)在end_index=3(c)的右边,因此方向从右往左取值,['f', 'e', 'd']
print(list[-2:-5:1])  # 1表示从左往右取值,start_index=-2(f)在end_index=3(c)的右边,因此方向从右往左取值,矛盾,[]

yield

首先上一个讲解yield很好的博文:https://blog.csdn.net/mieleizhi0522/article/details/82142856#commentBox

def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:", res)
g = foo()
print(next(g))
print("*"*20)
print(next(g))

"""
starting...
4
********************
res: None
4
"""
def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:",res)
g = foo()
print(next(g))
print("*"*20)
print(g.send(7))

"""
starting...
4
********************
res: 7
4
"""
5.程序执行g.send(7),程序会从yield关键字那一行继续向下运行,send会把7这个值赋值给res变量
6.由于send方法中包含next()方法,所以程序会继续向下运行执行print方法,然后再次进入while循环
7.程序执行再次遇到yield关键字,yield会返回后面的值后,程序再次暂停,直到再次调用next方法或send方法。

生成器 generator

L = [x * x for x in range(10)]
print(L)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
g = (x * x for x in range(10))
print(g)  # <generator object <genexpr> at 0x02F1D630>
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a+b
        n = n+1
    return 'done'

for i in fib(5):
    print(i)

# 为了获取return 'done',必须捕获StopIteration的异常
g = fib(5)
while True:
    try:
        print(next(g))
    except StopIteration as e:
        print('return %s' % e.value)
        break

序列化pickling、JSON

PythonJSON
dictobject
list, tuplearray
str, unicodestring
int, long, floatnumber
TRUETRUE
FALSEFALSE
Nonenull
方法描述
json.dumps()将 Python 对象编码成 JSON 字符串
json.loads()将已编码的 JSON 字符串解码为 Python 对象
json.dump()将Python内置类型序列化为json对象后写入文件
json.load()读取文件中json形式的字符串元素转化为Python类型
import json

t = ('lz', 18)
print('t:', json.dumps(t))

di = dict(name='\u7f57\u6b63', age='18')
print('di:', json.dumps(di, ensure_ascii=False))

d = {1:'a', 'b':2, 3: 4}
print('d:', json.dumps(d))

list = [{'a':'A', 2:'B', 'c':3}, ['d', 4], 'e', 5]
print('list:', json.dumps(list))
"""
t: ["lz", 18]
di: {"name": "罗正", "age": "18"}
d: {"1": "a", "b": 2, "3": 4}
list: [{"a": "A", "2": "B", "c": 3}, ["d", 4], "e", 5]
"""
import json
def json_to_dict():
    data = '''
    {
    "name": "Python书籍",
    "origin_price": 66,
    "pub_date": "2018-4-14 17:00:00",
    "store": ["京东", "淘宝"],
    "author": ["张三", "李四", "Jhone"],
    "is_valid": true,
    "is_sale": false,
    "meta": {
        "isbn": "abc-123",
        "pages": 300
    },
    "desc": null
    }
    '''
    res = json.loads(data)
    print(res)
    return res
if __name__ == '__main__':

    res1 = json_to_dict()
    print(type(res1))
"""
{'name': 'Python书籍', 'origin_price': 66, 'pub_date': '2018-4-14 17:00:00', 'store': ['京东', '淘宝'], 'author': ['张三', '李四', 'Jhone'], 'is_valid': True, 'is_sale': False, 'meta': {'isbn': 'abc-123', 'pages': 300}, 'desc': None}
<class 'dict'>
"""
Responses