Python笔记【四】

之前分享过一些python的笔记, 这儿是我的博客里 python学习的category,最近学习时有点新收获,再分享一些。

个人博客:https://blog.csdn.net/zyooooxie

zip()

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

在这里插入图片描述

传1个对象


# 当 zip()的参数是一个序列

s1 = 'zyooooxie'
z1 = zip(s1)
print(list(z1))
print()

t2 = ('1s', 787)
z2 = zip(t2)
print(list(z2))
print()

l3 = ['2', 178.01]
z3 = zip(l3)
print(list(z3))
print()

s4 = {66, 88.01, 's1'}
z4 = zip(s4)
print(list(z4))
print()

d5 = {'m': 'ai', 'gz': 'zz43', 'add': 'sz', 'w': 78.20}
z5 = zip(d5)
print(list(z5))         # key为 其采用的;
print()

b6 = b"Hello"
print(b6, str(b6, encoding="utf-8"), ord('H'), ord('e'), ord('l'), ord('o'))
z6 = zip(b6)                # bytes object
print(list(z6))

在这里插入图片描述

传多个对象


# 它的参数 如果是字典,那么键视为序列
d1 = {'name': 'zy', 'age': 88888}
d4 = {'sd': 'lxjx', 'zy': 'zyooooxie', 'blog': 'csdn'}
z1 = zip(d1, d4)
print(z1)
print(list(z1))
print()

l1 = ['sz', 888.11, 438522]
t2 = ('zy', 'zyooooxie', 'csdn', 'CSDN')
s3 = {44, 66, 22, 'zz'}
print(s3)
s1 = 'zyooooxie'
d5 = {'mm': 'aaa', 'gg': 'zz9999', 'dd': 'sz', 'ww': 11.22}
z4 = zip(l1, t2, s3, s1, d5)
print(list(z4))

在这里插入图片描述

请留意:zip object只能进行一次迭代遍历,第二次遍历就是空了


a = [1, 2, 3]
b = [4, 5, 6]
ab = zip(a, b)
print(list(ab))     # [(1, 4), (2, 5), (3, 6)]
# zip()之后的结果只能“使用一次”
# zip()实际上是一个Iterator, 不是Generator;
# 故使用list()获取zip()结果时,已经相当于是完成一次迭代遍历
# 第二次再次使用list()时迭代已经结束,所以返回[]
print(list(ab))     # []
print(list(ab))     # []


在这里插入图片描述


def test_zip():
    # zip(*iterables)
    # 创建一个聚合了来自每个可迭代对象中的元素的迭代器。

    # 返回一个元组的迭代器,其中的第i 个元组包含来自每个参数序列或可迭代对象的第i 个元素。
    # 当所输入可迭代对象中最短的一个被耗尽时,迭代器将停止迭代。
    # 当只有一个可迭代对象参数时,它将返回一个单元组的迭代器。
    # 不带参数时,它将返回一个空迭代器

    a = zip()
    print(a, type(a))
    print(list(a))

    b = zip((2, 22, 222, 2222, 22222))
    print(b, type(b))
    # print(*b)
    print(list(b))

    print(*zip({'a': '1', 'b': '1', 'c': '1', 'd': '1', 'e': '1', 'f': '1'}))

    # 函数会保证可迭代对象按从左至右的顺序被求值。
    c = zip((1, 11, 111), (3, 33, 333, 3333, 33333, 333333), (4, 44, 444, 4444))
    print(c, type(c))
    # print(*c)
    print(list(c))

    c = zip(dict(a=1, b=999, c=44), (55, 5, 55555, 5555, 555), {'一', '二', '四', '五', '三'})
    print(list(c))


    matrix = [[1, 2, 3, 4, 44],
              [5, 6, 7, 8, 88, 88],
              [9, 10, 11, 12, 12, 12, 12]]

    # 将交换其行和列
    abc = list(zip(*matrix))
    print(abc)

    # 当你不用关心较长可迭代对象末尾不匹配的值时,则zip() 只须使用长度不相等的输入即可。
    # 如果那些值很重要,则应改用 itertools.zip_longest()。

    pass

reversed()

在这里插入图片描述

list的reverse() 没有返回值,但是会对列表的对象进行排序【原地翻转 + 不创建新的list】;
reversed()是返回一个翻转后的 迭代器对象。

做对比的: list的sort() 和 sorted()
【sort() 只适用于列表,实现列表的原地排序,而sorted() 函数接受一切迭代器,返回一个排序后的新列表】

在这里插入图片描述


def test_reversed():
    # reversed(seq)
    # 返回一个反向的iterator。
    # seq 必须是一个具有__reversed__() 方法的对象或者是支持该序列协议(具有从0 开始的整数类型参数的__len__() 方法和__getitem__() 方法)。

    a = (1, 2, 2, 22, 44)
    abc = reversed(a)
    print(abc, type(abc))
    print(list(abc))
    print(list(abc))
    print(list(abc))

    print(list(reversed('654321')))
    print('-'.join(list(reversed('7654321'))))

    print(tuple(reversed((1, 22, 333, 4444))))

    # print(reversed({'12': 11, '34': 33, '56': 55, '789': 7}))   # 'dict' object is not reversible
    # print(list(reversed({123, 234, 456})))  # TypeError: 'set' object is not reversible

enumerate()

enumerate() 生成由 二元组(元素数量为2 的元组)构成的一个迭代对象,每个二元组由 索引号 及其对应的元素组成。

# 在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到

str_1 = 'zyooooxie'
for e in enumerate(str_1):
    print(e)

print()

tuple_1 = (78, 'sd', 2, None, 's111')
for e in enumerate(tuple_1):
    print(e)

print()

list_1 = [99999, 11, 222, 'k6k6k6k6k6k']
for e in enumerate(list_1):
    print(e)

print()

dict_1 = {'8': 74, 's': 0.25, True: (9, 11)}
for e in enumerate(dict_1):             # 对key的操作
    print(e)

在这里插入图片描述


"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
"""

def test_enumerate():
    # enumerate(iterable, start=0)
    # 返回一个枚举对象。iterable 必须是一个序列,或iterator,或其他支持迭代的对象

    test_list_p = [1, 2, 33, 444, 5, 66.66]
    enu_obj = enumerate(test_list_p)
    print(enu_obj)  # enumerate object

    # enumerate函数返回一个迭代器,迭代器的__next__() 方法返回一个元组,里面包含一个计数值(从start 开始,默认为0)和通过迭代iterable 获得的值。
    for e in enu_obj:
        print(e)

    print(list(enu_obj))  # []

    # start 默认从0开始,start不会影响对可迭代对象的遍历过程,只是改变计数值的起始值
    enu_obj = enumerate(test_list_p, start=3)
    print(list(enu_obj))

    enu_obj = enumerate(test_list_p, start=300)
    print(list(enu_obj))
    

def test_enumerate():
    # enumerate(iterable, start=0)
    # 返回一个枚举对象。iterable 必须是一个序列,或iterator,或其他支持迭代的对象

    test_list_p = [1, 2, 33, 444, 5, 66.66]
    enu_obj = enumerate(test_list_p)
    print(enu_obj)  # enumerate object

    # enumerate函数返回一个迭代器,迭代器的__next__() 方法返回一个元组,里面包含一个计数值(从start 开始,默认为0)和通过迭代iterable 获得的值。
    for e in enu_obj:
        print(e)

    print(list(enu_obj))  # []

    # start 默认从0开始,start不会影响对可迭代对象的遍历过程,只是改变计数值的起始值
    enu_obj = enumerate(test_list_p, start=3)
    print(list(enu_obj))

    enu_obj = enumerate(test_list_p, start=300)
    print(list(enu_obj))

isinstance()

仔细看前面的部分,就知道:zip() 和 reversed() 、enumerate() 的返回结果 是迭代器。
我们平常使用的list、dict、str、tuple,却不是Iterator(迭代器)
我怎么判断的呢?

看下:isinstance(object, classinfo)

如果参数 object 是参数 classinfo 的实例,返回True。

# python中的容器如列表、元组、字典、集合、字符串都是可迭代对象,但不是迭代器。可以用isinstance("abc", Iterator)来测试

from collections import Iterator
from collections import Iterable
from collections import Generator

list1 = [1, 2, 33]
t_1 = (438522, 22, 33.333)
s_1 = ['zy', 'zyooooxie', ('csdn', 'zy')]
str_1 = 'zyooooxie_csdn'
print(isinstance(list1, Iterator))
print(isinstance(t_1, Iterator))
print(isinstance(s_1, Iterator))
print(isinstance(str_1, Iterator))

print()

zip_1 = zip(t_1, s_1)

print(isinstance(zip_1, Iterator))
print(isinstance(zip_1, Iterable))
print(isinstance(zip_1, Generator))
print(list(zip_1))
print(list(zip_1))
print(list(zip_1))

print()

s_11 = reversed(s_1)
print(isinstance(s_11, Iterator))
print(isinstance(s_11, Iterable))
print(isinstance(s_11, Generator))
print(list(s_11))
print(list(s_11))
print(list(s_11))
print()


e_1 = enumerate(s_1)
print(isinstance(e_1, Iterator))
print(isinstance(e_1, Iterable))
print(isinstance(e_1, Generator))
print(list(e_1))
print(list(e_1))
print(list(e_1))

在这里插入图片描述


def test_isinstance():
    # isinstance(object, classinfo)
    # 如果参数object 是classinfo 的实例或者是其(直接、间接或虚拟) 子类则返回True。如果object不是给定类型的对象,函数将总是返回False。

    # 如果classinfo 是类型对象元组,那么如果object 是其中任何一个类型的实例就返回True。
    # 如果classinfo 既不是类型,也不是类型元组或类型元组的元组,则将引发TypeError 异常。

    a = list()
    print(isinstance(a, list))
    print(isinstance(a, tuple))
    print(isinstance(a, (tuple, list)))

    print(isinstance(list, list))
    print(isinstance(list, a))  # TypeError: isinstance() arg 2 must be a type or tuple of types

生成器 Generator

在 Python 中,使用了 yield 的函数被称为生成器(generator);


# 与普通函数不同,生成器函数被调用后,其函数体内的代码并不会立即执行,而是返回一个生成器(generator)。
# 当返回的生成器调用成员方法时,相应的生成器函数中的代码才会执行。


def my_gene_func_2():
    index = 0
    list_a = [1, 222, 66, 88, 55, 4444, 10000, 888, 9999, 55, 33.3333]
    while True:
        print(index, '索引')

        yield list_a[index]
        index += 1

aBc = my_gene_func_2()
print(aBc)
print(aBc.__iter__)
print(aBc.__next__)

print()

print(next(aBc))
print(next(aBc))
print(next(aBc))
print(next(aBc))

aBc.close()             # 告诉生成器函数,当前生成器作废不再使用


# print(next(aBc))              # StopIteration


# next()时,my_gene_func_2() 从上一次暂停的位置开始,一直执行到下一个 yield 表达式,将 yield 关键字后的表达式列表返回给调用者,并再次暂停。
# 注意,每次从暂停恢复时,生成器函数的内部变量、指令指针、内部求值栈等内容和暂停时完全一致。

在这里插入图片描述

def gen_example_2():
    yield 1
    yield 2
    yield 11
    yield 12
    yield 21
    yield 22
    yield 31
    yield 32
    yield 41
    yield 42

# for语句能自动捕获StopIteration异常,所以generator(本质上是任何iterator)较为常用的方法是在循环中使用
f = gen_example_2()
print('调用gen_example_2()并没有输出任何内容')
print('说明函数体的代码尚未开始执行')
print('当调用generator的next方法,generator会执行到yield表达式处,返回yield表达式的内容,然后暂停(挂起)在这个地方')
print('暂停意味着方法的局部变量,指针信息,运行环境都保存起来,直到下一次调用next方法恢复')
print('第二次调用next之后就暂停在 后一个yield; 最后一次 调用next()方法,则会抛出StopIteration异常')
print()

for i in f:
    print(i, '内容')

print()
print()
print('..............')


for i in f:
    print(i, '啊啊啊啊啊啊啊啊')

print('..............')
print()
print()


p = gen_example_2()
print(list(p))
print(list(p))

在这里插入图片描述

for循环的过程就是执行next方法的过程,经历过一次for循环以后,在for循环的内部,已经抛出StopIteration异常,for循环在捕捉到这个异常后停止遍历,因此第二次for循环时不会产生任何效果。

所以生成器 是会出现前面提到的 第二次遍历为空的情况。
生成器被完整遍历一次后,就无法再次遍历

并行迭代-zip()

通过zip()函数对多个序列进行并行迭代。(可以用作任意数量的序列,并且可以应付不等长的序列;当短序列用完就会停止。)

这一趴 来自 造数据:

我想造N条数据,一般先准备好 各字段的list。

field_a = [55, 66, 77, 88, 99, 100, 111]                         # 体重
field_b = [2000, 2001, 2002, 2005, 2006, 2007, 2008]            # 薪资
field_c = [0, 0, 0, 1, 1, 1, 1]                                 # 性别
field_d = ['a', 'b', 'c', 'r', 's', 't', 'u']                   # 姓名

这造数据的要求是:
每个元素为 性别、薪资、体重、姓名【field_d的 (index +1) + 此index的元素】

第一版:

data = list()
num = 7
for f in range(num):
    n_index = range(num).index(f)
    ele1 = field_a[n_index]
    ele2 = field_b[n_index]
    ele3 = field_c[n_index]
    ele4 = ''.join([str(n_index + 1), field_d[n_index]])
    ele = (ele3, ele2, ele1, ele4)

    data.append(ele)

print(data)

第二版:

data = list()

for gender, salary, weight in zip(field_c, field_b, field_a):
    ele = (gender, salary, weight)
    n_index = field_a.index(weight)
    ele += (''.join([str(n_index + 1), field_d[n_index]]), )

    data.append(ele)

print(data)

第三版:

data = list()
for ele in zip(field_c, field_b, field_a):
    n_index = list(zip(field_c, field_b, field_a)).index(ele)
    ele += (''.join([str(n_index + 1), field_d[n_index]]),)

    data.append(ele)

print(data)

第四版:


data = list()
for i, ele in enumerate(zip(field_c, field_b, field_a)):
    ele += (''.join([str(i + 1), field_d[i]]),)

    data.append(ele)

print(data)

列表切片的删除、重新赋值

A. 删除某列表切片

old_list = ['zyooooxie', 'csdn', 'zy', 438522.001, 'zy_oooo_xie', ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}]
print(old_list)

# 列表切片赋值给某变量;原列表不改变
a_list = old_list[:2]

del a_list

print(old_list)

print()

# del删除某列表的切片【此切片没有赋值给某变量】;原列表内容改变
del old_list[:2]
print(old_list)

在这里插入图片描述

B.某列表切片重新赋值

我把情况分 等长、不等长来说 【实际都一样 = = 】


# 等长切片赋值,即用同样数量的元素去替换目标对象的元素

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}]
print(test_list)

test_list[2:5] = '890'              # 字符串转为字符列表 ['8', '9', '0']
print(test_list)
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}]
test_list[2:5] = ('0', '1', '2')
print(test_list)
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}]
print(test_list[4:4])
test_list[4:4] = list()
print(test_list)
print()


test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}]
print(test_list[4:4])
test_list[4:4] = tuple()
print(test_list)
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}]

print(test_list[4:4])
test_list[4:4] = set()
print(test_list)
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}]
print(test_list[4:4])
test_list[4:4] = ''
print(test_list)
print()

在这里插入图片描述

# 不等长切片赋值--同样替换

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
print(test_list)

test_list[4:5] = '1238574'
print(test_list)
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
print(test_list[5:5])                          # 空列表
test_list[5:5] = [85, 96, 52]                   # 对一个空切片进行赋值 ,即是在其索引处出插入数据
print(test_list)
print()


test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
test_list[6:8] = []                         # 使用一个空列表进行对切片进行赋值,将会是把切片的数据删除掉,相当于del
print(test_list)
print()


test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
test_list[6:8] = ('we', 'are', 'doc', '     ')                 # 可迭代类型
print(test_list)
print()


test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
test_list[4:] = ('we', 'are', 'doc', '  zy   3')                 # 可迭代类型
print(test_list)
print()


test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
test_list[:5] = ('we', 'are', 'doc', '1   zy  ')                 # 可迭代类型
print(test_list)


print()
print()
print()
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
test_list[1:5] = range(1, 5)
print(test_list)
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
test_list[1:5] = range(1, 8)
print(test_list)
print()

test_list = ['zyooooxie', 'csdn', 100, 438522.001, {'zy': 'zyooooxie'}, ('csdn', 438522), {'csdn', 'zyooooxie', 'sd'}, True, None, [1, 2, 3]]
test_list[1:5] = range(1, 3)
print(test_list)

在这里插入图片描述

这2天,我发现有些网站在转载我的博客,但是没有经过我的授权,我很愤怒;

重申下我的原则:原创作品,谢绝转载!

个人博客 https://blog.csdn.net/zyooooxie

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值