在处理列表时,如何使用.pop和.append做FIFO(代替LIFO)?

时间:2019-09-16 17:10:38

标签: python

我正在使用《 Python崩溃教程》这本书学习python,并在用用户输入填充列表上进行了练习。我在下面完成了此练习,但想学习如何更改代码,以使列表的顺序匹配。

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

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())

与“ sandwich_orders”列表相反地打印“ current_sandwich”列表。我希望current_sandwich以与sandwich_orders列表相同的顺序打印。

2 个答案:

答案 0 :(得分:1)

您可以在位置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)

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

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

答案 1 :(得分:0)

deque API与list API相似。您仍然可以使用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())