美文网首页python学习交流
python 定制类:索引与切片

python 定制类:索引与切片

作者: 水之心 | 来源:发表于2018-12-08 21:44 被阅读4次

__getitem__ 和 slice 切片

__getitem__ 的简单用法:

当一个类中定义了 __getitem__ 方法,那么它的实例对象便拥有了通过下标来索引的能力。

class A:
    def __getitem__(self, item):
        return item


a = A()
print(a[5], a[12])
5 12

__getitem__ 实现斐波那契数列:

class Fib:
    def __getitem__(self, item):
        if item == 0 or item == 1:
            return 1
        else:
            a, b = 1, 1
            for i in range(item - 1):
                a, b = b, a + b
            return b


fib = Fib()
for i in range(10):
    print(fib[i])
1
1
2
3
5
8
13
21
34
55

slice 切片

我们发现上个程序 fib[2] 这样的一个下标是没问题的,不过 fib[3:5] 这样的切片的话是会报错的。所以我们先了解下什么是切片。

a = slice(10)
a
slice(None, 10, None)
a = slice(1,10,2)
print(a.start)
print(a.stop)
print(a.step)
a
1
10
2





slice(1, 10, 2)
li = [1,2,3,4,5,6,7,8,9,0]
li[slice(2,6)]
[3, 4, 5, 6]

给斐波那契数列完成 slice 切片:

class Fib(object):
    def __getitem__(self, item):
        if isinstance(item, slice):
            print(item.start)
            print(item.stop)

            stop = item.stop
            if item.stop is None:
                stop = 100

            re_list = []

            a, b = 0, 1
            for i in range(stop):
                a, b = b, a + b
                re_list.append(a)

            return re_list[item.start:stop:item.step]

        elif item == 0 or item == 1:
            return 1
        else:
            a, b = 1, 1
            for i in range(item - 1):
                a, b = b, a + b
            return b


fib = Fib()
print(fib[1:20:2])
1
20
[1, 3, 8, 21, 55, 144, 377, 987, 2584, 6765]

相关文章

  • python 定制类:索引与切片

    __getitem__ 和 slice 切片 __getitem__ 的简单用法: 当一个类中定义了 __geti...

  • 数组的索引和切片

    索引: 获取数组中特定位置元素的过程切片: 获取数组元素子集的过程 一维数组的索引和切片: 与Python的列表类...

  • Numpy数组的索引与切片和变形拼接分裂

    1.概述 今天我们来讲一下Numpy数组的索引与切片,numpy数组的索引与切片和Python中的切片与索引的作用...

  • Python中的索引与切片

    Python中的索引与切片 一、索引 二、一维数据切片 ​ 一个完整的切片表达式包含两个":",用于分...

  • 4个Python提效用法

    索引和切片 Python中获取列表中的任意元素。除了支持常见的正索引外, Python还支持负索引和切片。 正索引...

  • python的学习笔记10

    13、索引的使用 ndarray对象的内容可以通过索引或切片来访问和修改,与 Python 中 list 的切片操...

  • python:numpy的索引和切片(2)

    接一章 python:numpy的索引和切片(1)python:numpy的索引和切片(1) 1、numpy中数值...

  • Python数据分析学习

    当数据索引不是整数时: 利用标签切片运算与普通的Python切片运算不同,末端是包含的 当数据索引不是整数时:

  • python学习_01

    python的数字类型、字符串、索引、切片讲解 python的数据类型 【重点学习】字符串【表示、索引、切片、内置...

  • python定制类__getitem__()方法

    今天在学习python的定制类,教程里面展示了如何用__getitem__方法,实现某个类的切片。pythoncl...

网友评论

    本文标题:python 定制类:索引与切片

    本文链接:https://www.haomeiwen.com/subject/btychqtx.html