【问题标题】:Calling a item from a queue data structure list (Python)从队列数据结构列表中调用项目 (Python)
【发布时间】:2026-01-09 04:35:01
【问题描述】:

我正在尝试将 3 个人排入列表中,以在顶部显示每个人的所有姓名的结果,但只能获得一个没有任何姓名的结果:

Contacting the following  
Phone answered: Yes  
Booked an appointment: No  
Reshedule an appointment again.

我想让输出显示他们的所有姓名和 3 个输出,每个人一个来自存储在 'names' 中的信息,并且每个名称不会出现两次。

我想使用队列根据列表对它们进行优先级排序,因此我试图将它们按顺序排列。 if 和 elif 是根据随机生成器属于任一类别的条件。现在,只是没有定义包含名称的方法。

代码

import random

class Queue:
    def __init__(self):
        self.container = []

    def isEmpty(self):
        return self.size() == 0  

    def enqueue(self, item):
        self.container.append(item)

    def dequeue(self):
        self.container.pop(0)

    def size(self):
        return len(self.container)

    def peek(self) :
        return self.container[0]

names = ["Alvin", "James", "Peter"]

# Enqueuing

q = Queue()
q.enqueue(random.choice(names))

# Dequeuing and Printing
print("Contacting the following:\n" + "\n".join(q.container))  # unsure about this




for i in range(q.size()):

    answered = random.randint(0,1)
    booked = random.randint(0, 1)

    if(answered == 1 and booked == 1):
        print("Now Calling -" + (q.names)) # unsure about this
        print("Phone answered: Yes")
        print("Booked an appointment: Yes")
        print("Booking successful.")

    elif(answered==1 and booked==0):
        print("Now Calling -" + (q.names)) # unsure about this
        print("Phone answered: Yes")
        print("Booked an appointment: No")
        print("Reshedule an appointment again.")

    elif(answered == 0):
        print("Now Calling -" + (q.names)) # unsure about this
        print("Phone answered: No")
        print("Reshedule a callback.")

    q.dequeue()

所需输出示例:

Contacting the following
Alvin
James
Peter

Now Calling - James
Phone answered: No
Reshedule a callback.

【问题讨论】:

  • 当你删除它时,我正在给你的previous question写一个答案......
  • 很抱歉。我以为我会自己想办法。

标签: python data-structures queue


【解决方案1】:

我对您的队列class 进行了一些更改。主要是.dequeue方法没有返回它弹出的项目,所以它返回默认值None

我还将.size 方法更改为__len__,这样您就可以将Queue 实例传递给内置的len 函数。并给它一个iter 方法,你可以轻松地在for 循环中使用它,或者将它传递给.join。我还将 .isEmpty 更改为 .is_empty 以符合 Python 的 PEP-0008 样式指南。

由于您希望将每个名称随机添加到队列中而不重复,我们不希望在此处使用random.choice。相反,我们可以使用random.shuffle;另一种选择是使用random.sample,尽管当您想从列表中进行部分选择时,这更合适。

from random import seed, shuffle, randrange

# Seed the randomizer so we can reproduce results while testing
seed(9)

class Queue:
    def __init__(self):
        self.container = []

    def __len__(self):
        return len(self.container)

    def is_empty(self):
        return len(self) == 0

    def enqueue(self, item):
        self.container.append(item)

    def dequeue(self):
        return self.container.pop(0)

    def peek(self) :
        return self.container[0]

    def __iter__(self):
        return iter(self.container)

names = ["Alvin", "James", "Peter"]

# Enqueuing
q = Queue()

# Make a temporary copy of the names that we can 
# shuffle without affecting the original list
temp = names.copy()
shuffle(temp)

# Put the shuffled names onto the queue
for name in temp:
    q.enqueue(name)

# Dequeuing and Printing
print("Contacting the following")
print('\n'.join(q))
#for name in q:
    #print(name)

while not q.is_empty():
    name = q.dequeue()
    print('\nNow Calling -', name)

    answered = randrange(2)
    booked = randrange(2)

    if answered:
        print("Phone answered: Yes")
        if booked:
            print("Booked an appointment: Yes")
            print("Booking successful.")
        else:
            print("Booked an appointment: No")
            print("Reshedule an appointment again.")
    else:
        print("Phone answered: No")
        print("Reshedule a callback.")

输出

 Contacting the following
Alvin
Peter
James

Now Calling - Alvin
Phone answered: Yes
Booked an appointment: No
Reshedule an appointment again.

Now Calling - Peter
Phone answered: No
Reshedule a callback.

Now Calling - James
Phone answered: Yes
Booked an appointment: Yes
Booking successful.

在上面我使用的代码中

print('\n'.join(q))

打印所有名称,因为您在代码中为此目的使用了.join。但我也展示了使用简单的for 循环的替代方法,但我将其注释掉了:

for name in q:
    print(name)

【讨论】:

  • 在输出中,它显示了 Alvin、Peter、James 而不是列表中的 names = ["Alvin", "James", "Peter"]。有没有办法让我按顺序排列?
  • 另外,我一直得到相同的结果,似乎它自己洗牌。
  • @John 您的代码使用random.choice,所以我认为您想以随机顺序将名称添加到队列中。如果您希望名称按原始顺序排列,那么只需排列 names 并去掉 temp 的东西。我的代码使用random.shuffle,这样随机名称就不会重复。它在每次运行时选择相同的随机顺序,因为我们使用seed(9) 播种随机数。如果您将该行注释掉,那么每次都会选择不同的随机顺序。
  • 谢谢。如果我想在名称前面按升序添加 1-3 的数字for name in q: print(name) 我是否使用类似这样的东西for name in q: print((number += 1) + "-" + name)
  • @John Python 不允许你在表达式中做赋值,所以你不能做像(number += 1) 这样的东西。做你想做的最好的方法是使用内置的enumerate 函数。例如,for i, name in enumerate(q, 1): print('{}-{}'.format(i, name))