python3使用编程技巧进阶笔记3

  1. 如何对迭代器进行切片操作
# 方法1,_getitem_()方法
test = list(range(10))
res1 = test.__getitem__(0)
print(res1) # 0
res2 = test.__getitem__(slice(0,2))
print(res2) # [0, 1]

# 方法2,islice()方法
from itertools import islice
res3 = islice(test, 0, 4)
print(res3) # [0, 1, 2, 3]
res4 = islice(test, 0, 4, 1)
print(res4) # [0, 1, 2, 3]
res5 = islice(test, 0, 4, 2)
print(res5) # [0, 2]
  1. 如何在for循环中迭代多个可迭代对象
from random import randint
# 用zip函数
test1 = list(randint(0, 10) for _ in range(10))
test2 = list(randint(10, 20) for _ in range(10))
test3 = list(randint(20, 30) for _ in range(10))
print(test1)
print(test2)
print(test3)
test = []
for res1, res2, res3 in zip(test1, test2, test3):
    test.append(res1 + res2 + res3)
print(test)
#[8, 2, 2, 8, 6, 9, 4, 0, 9, 1]
#[18, 10, 18, 10, 20, 19, 20, 20, 17, 18]
#[30, 23, 26, 22, 24, 24, 30, 24, 30, 29]
#[56, 35, 46, 40, 50, 52, 54, 44, 56, 48]

# 第2种方法,chain函数可以按行连接多个可迭代对象
from itertools import chain
demo = [x for x in chain(test1, test2, test3) if x % 2 ==0]
print(demo)
# [9, 5, 5, 0, 6, 2, 3, 4, 6, 6]
#[17, 16, 15, 16, 19, 12, 18, 15, 15, 19]
#[24, 21, 29, 24, 30, 29, 24, 24, 20, 20]
#[0, 6, 2, 4, 6, 6, 16, 16, 12, 18, 24, 24, 30, 24, 24, 20, 20]
  1. 如何派生内置不可变类型并修其改实例化行为
# 继承内置tuple类,实现__new__(),在其中修改实例化行为
class IntTuple(tuple):
    def __new__(cls, iterable):
    # 过滤掉元组中小于零并且不是整数的元素
        demo = (i for i in iterable if isinstance(i, int) and i > 0)
        return super().__new__(cls, demo)


test = IntTuple([-2, -4, -5, 0, 0.2, 8, 9])
print(test) # (8, 9)
  1. 如何创建可管理的对象属性
# 使用property装饰器
class Student():
    def __init__(self, score):
        self.score = score

    @property
    def value(self):
        return self.score

    @value.setter
    def value(self, score):
        if not isinstance(score, int):
            raise TypeError("wrong type")
        self.score = score


test = Student(66)
print(test.value) # 66
test.value = 88
print(test.value) # 88
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

guizhouspiderman

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值