如何在处理列表时使用 .pop 和 .append 进行 FIFO(而不是 LIFO)?



我正在使用Python速成课程书学习python,做用用户输入填充列表的练习。 我在下面完成了这个练习,但想学习如何更改代码以使列表的顺序匹配。

我读到Python列表作为FIFO,LIFO队列使用deque,但还不了解如何使用这些数据结构。

sandwich_orders = ['cheese', 'ham', 'turkey', 'pb&j', 'chicken salad']
finished_sandwiches = []
for sandwich in sandwich_orders:
print("I received your " + sandwich + " sandwich order.")
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("Making " + current_sandwich.title() + " sandwich.")
finished_sandwiches.append(current_sandwich)
print("nThe following sandwiches have been made:")
for sandwich in finished_sandwiches:
print(sandwich.title())

打印current_sandwich列表的顺序与sandwich_orders列表的顺序相反。 我想current_sandwich按照与sandwich_orders列表相同的顺序打印。

您可以将list.insert与位置0一起使用,而不是list.append

while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("Making " + current_sandwich.title() + " sandwich.")
finished_sandwiches.insert(0, current_sandwich)

您也可以从位置0list.pop并使用list.append

while sandwich_orders:
current_sandwich = sandwich_orders.pop(0)
print("Making " + current_sandwich.title() + " sandwich.")
finished_sandwiches.append(current_sandwich)
deque

API类似于listAPI。您仍然可以使用append添加新元素。您只需使用popleft而不是pop来移除最左侧的元素。

from collections import deque
sandwich_orders = deque(['cheese', 'ham', 'turkey', 'pb&j', 'chicken salad'])
finished_sandwiches = deque()
for sandwich in sandwich_orders:
print("I received your " + sandwich + " sandwich order.")
while sandwich_orders:
current_sandwich = sandwich_orders.popleft()
print("Making " + current_sandwich.title() + " sandwich.")
finished_sandwiches.append(current_sandwich)
print("nThe following sandwiches have been made:")
for sandwich in finished_sandwiches:
print(sandwich.title())

最新更新