class Fib(object):
# ==========可以索引或者切片取值(带步长)===============
def __getitem__(self, n):
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice): # n是切片
start = n.start
stop = n.stop
step = n.step
L = []
if start is None:
start = 0
if step is None: # 步长缺省值为1
step = 1
for x in range(stop):
if x >= start:
if (x % step == 0):
L.append(a)
return L
# # 索引
# f = Fib()
# print(f[100])
# 切片(带步长)
f = Fib()
print(f[:10]) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print(f[:10:2]) # [1, 2, 5, 13, 34]
print(f[:10:3]) # [1, 3, 13, 55]
Sign in to make a reply
o0stanley0o
class Fib(object):
# ==========可以索引或者切片取值(带步长)===============
def __getitem__(self, n):
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice): # n是切片
start = n.start
stop = n.stop
step = n.step
a, b = 1, 1
L = []
if start is None:
start = 0
if step is None: # 步长缺省值为1
step = 1
for x in range(stop):
if x >= start:
if (x % step == 0):
L.append(a)
a, b = b, a + b
return L
# # 索引
# f = Fib()
# print(f[100])
# 切片(带步长)
f = Fib()
print(f[:10]) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print(f[:10:2]) # [1, 2, 5, 13, 34]
print(f[:10:3]) # [1, 3, 13, 55]