实际案例
很多应用程序都有浏览用户的历史记录的功能,如:
- 浏览器可以查看最近访问过的网页;
- 视频播放器可以查看最近播放过的视频文件;
- Shell可以查看用户输入过的命令;
......
按照上面功能的描述,可以使用collections 下的deque的队列,也是双端队列
In [1]: from collections import <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/deque" title="View all posts in deque" target="_blank">deque</a></span> In [2]: q = <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/deque" title="View all posts in deque" target="_blank">deque</a></span>([], 5) # 初始值是[],数量限定是5, In [3]: q Out[3]: deque([]) In [4]: q.append(q) In [5]: q Out[5]: deque([deque(...)]) In [6]: q.append(1) In [8]: q.append(3) In [9]: q.append(4) In [10]: q Out[10]: deque([deque(...), 1, 3, 4]) In [11]: q.append(5) In [12]: q.append(6) In [13]: q Out[13]: deque([1, 3, 4, 5, 6]) In [14]:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
In
[
1
]
:
from
collections
import
deque
In
[
2
]
:
q
=
deque
(
[
]
,
5
)
# 初始值是[],数量限定是5,
In
[
3
]
:
q
Out
[
3
]
:
deque
(
[
]
)
In
[
4
]
:
q
.
append
(
q
)
In
[
5
]
:
q
Out
[
5
]
:
deque
(
[
deque
(
.
.
.
)
]
)
In
[
6
]
:
q
.
append
(
1
)
In
[
8
]
:
q
.
append
(
3
)
In
[
9
]
:
q
.
append
(
4
)
In
[
10
]
:
q
Out
[
10
]
:
deque
(
[
deque
(
.
.
.
)
,
1
,
3
,
4
]
)
In
[
11
]
:
q
.
append
(
5
)
In
[
12
]
:
q
.
append
(
6
)
In
[
13
]
:
q
Out
[
13
]
:
deque
(
[
1
,
3
,
4
,
5
,
6
]
)
In
[
14
]
:
|
如果deque的定义不太理解,可以查看这篇文章
我们试着实现最初的目的
# -*- coding: utf-8 -*- __author__ = 'songhao' from collections import deque from random import randint nu = randint(0,100) history = deque([], 5) # 创建个序列,数量为五个元素 def guess(n): if n == nu: return True elif n > nu: print("你输入的数值有点大了") return False else: print("你输入的数值有点小了") return False while True: n = input("请输入你想猜测的值") if n.isdigit(): n = int(n) history.append(n) if guess(n): break elif n == 'h?': print(list(history))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
# -*- coding: utf-8 -*-
__author__
=
'songhao'
from
collections
import
deque
from
random
import
randint
nu
=
randint
(
0
,
100
)
history
=
deque
(
[
]
,
5
)
# 创建个序列,数量为五个元素
def
guess
(
n
)
:
if
n
==
nu
:
return
True
elif
n
>
nu
:
print
(
"你输入的数值有点大了"
)
return
False
else
:
print
(
"你输入的数值有点小了"
)
return
False
while
True
:
n
=
input
(
"请输入你想猜测的值"
)
if
n
.
isdigit
(
)
:
n
=
int
(
n
)
history
.
append
(
n
)
if
guess
(
n
)
:
break
elif
n
==
'h?'
:
print
(
list
(
history
)
)
|