0

我正在使用 Python Crash Course book 学习 python,在使用用户输入填充列表时进行练习。我在下面完成了这个练习,但想学习如何更改代码以使列表的顺序匹配。

我阅读了 Python 列表作为 FIFO,使用双端队列的 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())

打印 current_sandwich 列表的顺序与 Sandwich_orders 列表相反。我希望 current_sandwich 以与 Sandwich_orders 列表相同的顺序打印。

4

2 回答 2

1

dequeAPI 类似于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())
于 2019-09-16T17:24:24.897 回答
1

您可以使用list.insertwith position0代替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)
于 2019-09-16T17:12:50.027 回答