在列表中显示计数而不是项名称(Python)
我试图让下面的程序显示输出中可用水果的数量,而不是显示水果的名称,但我无法找出原因。我如何纠正它 基本上,程序将生成一个从1到5的随机数,如果生成的数小于3(1或2),则不可用,如果大于3,则可用在列表中显示计数而不是项名称(Python),python,data-structures,queue,Python,Data Structures,Queue,我试图让下面的程序显示输出中可用水果的数量,而不是显示水果的名称,但我无法找出原因。我如何纠正它 基本上,程序将生成一个从1到5的随机数,如果生成的数小于3(1或2),则不可用,如果大于3,则可用 import random class Queue: def __init__(self): self.container = [] def __len__(self): return len(self.container) def is_
import random
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)
fruits = ["Apple", "Orange", "Pear", "Watermelon"]
q = Queue()
temp = fruits.copy()
fruits = ["Apple", "Orange", "Pear", "Watermelon"]
d = {fruit: random.randint(1, 5) for fruit in fruits}
unavailable = [fruit for fruit in d if d[fruit] < 3]
available = [fruit for fruit in d if d[fruit] >= 3]
for fruit in fruits:
if random.randint(1, 5) < 3:
unavailable.append(fruit)
else:
available.append(fruit)
percent_available = len(available) / (len(available) + len(unavailable)) * 100
for fruit in temp:
q.enqueue(fruit)
print(fruit)
numgen = random.randint(1, 5)
if(numgen >= 3):
print("Item is available")
else:
print("Item is unavailable")
print("The following items are unavailable")
print(unavailable)
print('Number of fruits available = ' + str(available))
print('Percentage of fruits available = ' + str(percent_available))
更改此行:
print('Number of fruits available = ' + str(available))
关于这一行:
print('Number of fruits available = {}'.format(len(available)))
输出:
Apple
Item is unavailable
Orange
Item is unavailable
Pear
Item is unavailable
Watermelon
Item is available
The following items are unavailable
['Apple', 'Orange', 'Pear']
Number of fruits available = 5
Percentage of fruits available = 62.5
使用
len(我的列表)
?我应该在中使用哪个部分?也发布预期输出。
Apple
Item is unavailable
Orange
Item is unavailable
Pear
Item is unavailable
Watermelon
Item is available
The following items are unavailable
['Apple', 'Orange', 'Pear']
Number of fruits available = 5
Percentage of fruits available = 62.5