1 def my_range(start, stop = None, step = 1):
2 # 实现自己的 range
3 if stop == None:
4 start, stop = 0, start
5
6 result = []
7 if step > 0:
8 i = start
9 while i < stop:
10 result.append(i)
11 i += step
12 else:
13 i = start
14 while (i > stop):
15 result.append(i)
16 i += step
17 return result
18
19 print(my_range(10))
20 print(my_range(5, 20, 2))
21 print(my_range(1, 10))
22 print(my_range(10, 0, -1))
23 print(my_range(100, 0, -9))
输出:
>>>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 7, 9, 11, 13, 15, 17, 19]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[100, 91, 82, 73, 64, 55, 46, 37, 28, 19, 10, 1]
posted on 2013-05-16 21:00
unixfy 阅读(376)
评论(0) 编辑 收藏 引用