Python range函式 實現

2022-09-07 13:36:14 字數 2210 閱讀 3522

def my_range(start, end=none, step=1):

result =

beg = none

if end == none:

beg = 0

final = start-1

else:

beg = start

if step >0:final = end-1

else: final = end+1

if step > 0:

while beg<=final:

yield beg

beg +=step

elif step < 0:

while final<=beg:

yield beg

beg +=step

else:

raise baseexception("step not allow 0")

for i in my_range(-1,-1):

print(i)

class myrange:

def __init__(self, start, stop=none, step=none):

# 模擬range從0開始的行為

if stop is none:

self.start = 0

self.stop = start - 1

else:

self.start = start

self.stop = stop - 1

self.step = step

# 保留原始引數

self.origin_start = self.start

self.origin_stop = self.stop + 1

self.origin_step = self.step

def __repr__(self):

""":return: 顯示表現

"""if self.origin_step:

result = '{}({}, {}, {})'.format(

self.__class__.__name__,

self.origin_start,

self.origin_stop,

self.origin_step

)else:

result = '{}({}, {})'.format(

self.__class__.__name__,

self.origin_start,

self.origin_stop

)return result

def __iter__(self):

return self

def __next__(self):

""":return: 返回當前數字,然後在當前數字上+1

"""result = self.start

if self.start <= self.stop:

self.start += 1

else:

raise stopiteration

return result

def __getitem__(self, item):

""":param item: 如果是單個數字, 那麼item的型別將會是int,

如果是分片那麼item將會是乙個slice.

:return: 返回分片結果

"""def is_index_error(_start):

if _start > self.stop:

raise indexerror('分片不得大於最大值.')

if isinstance(item, int):

result = self.origin_start + item

is_index_error(result)

elif isinstance(item, slice):

start = self.origin_start + item.start

stop = self.origin_start + item.stop

list(map(is_index_error, myrange(start, stop)))

result = myrange(start, stop)

else:

raise keyerror

return result

Python range 函式用法

python range 函式可建立乙個整數列表,一般用在 for 迴圈中。range start,stop step 引數說明 range 10 從 0 開始到 10 0,1,2,3,4,5,6,7,8,9 range 1,11 從 1 開始到 11 1,2,3,4,5,6,7,8,9,10 ra...

Python range 函式用法

python range 函式可建立乙個整數列表,一般用在 for 迴圈中。range start,stop step 引數說明 range 10 從 0 開始到 10 0,1,2,3,4,5,6,7,8,9 range 1,11 從 1 開始到 11 1,2,3,4,5,6,7,8,9,10 ra...

Python range 函式用法

python range 函式用法 python 內建函式 python 內建函式 python range 函式可建立乙個整數列表,一般用在 for 迴圈中。函式語法 range start,stop step 引數說明 start 計數從 start 開始。預設是從 0 開始。例如range 5...