>>>
range
(
1
,
5
)
#代表从1到5(不包含5)
[
1
,
2
,
3
,
4
]
>>>
range
(
1
,
5
,
2
)
#代表从1到5,间隔2(不包含5)
[
1
,
3
]
>>>
range
(
5
)
#代表从0到5(不包含5)
[
0
,
1
,
2
,
3
,
4
]
array
=
[
1
,
2
,
5
,
3
,
6
,
8
,
4
]
#其实这里的顺序标识是
[
1
,
2
,
5
,
3
,
6
,
8
,
4
]
(
0
,
1
,
2
,
3
,
4
,
5
,
6
)
(
-
7
,
-
6
,
-
5
,
-
4
,
-
3
,
-
2
,
-
1
)
>>>
array[
0
:]
#列出0以后的
[
1
,
2
,
5
,
3
,
6
,
8
,
4
]
>>>
array[
1
:]
#列出1以后的
[
2
,
5
,
3
,
6
,
8
,
4
]
>>>
array[:
-
1
]
#列出-1之前的
[
1
,
2
,
5
,
3
,
6
,
8
]
>>>
array[
3
:
-
3
]
#列出3到-3之间的
[
3
]
那么两个[::]会是什么那?
>>>
array[:: 2 ] [ 1 , 5 , 6 , 4 ] >>>
array[ 2 ::] [ 5 , 3 , 6 , 8 , 4 ] >>>
array[:: 3 ] [ 1 , 3 , 4 ] >>>
array[:: 4 ] [ 1 , 6 ] 如果想让他们颠倒形成reverse函数的效果 >>>
array[:: - 1 ] [ 4 , 8 , 6 , 3 , 5 , 2 , 1 ] >>>
array[:: - 2 ] [ 4 , 6 , 5 , 1 ] |
这两个输出的结果都是一样的,实际上不同,range会直接生成一个list对象:
a = range(0,100)
print type(a)
print a
print a[0], a[1]
而xrange则不会直接生成一个list,而是每次调用返回其中的一个值
a = xrange(0,100)
print type(a)
print a
print a[0], a[1]
xrange做循环的性能比range好,尤其是返回很大的时候!
尽量用xrange吧,除非你是要返回一个列表。
- >>> xrange(5)
- xrange(5)
- >>> list(xrange(5))
- [0, 1, 2, 3, 4]
- >>> xrange(1,5)
- xrange(1, 5)
- >>> list(xrange(1,5))
- [1, 2, 3, 4]
- >>> xrange(0,6,2)
- xrange(0, 6, 2)
- >>> list(xrange(0,6,2))
- [0, 2, 4]
while i<10:
print i
i+=1
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'
输出
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done