我正在尝试让以下程序显示输出中可用的水果数量,而不是显示水果的名称,但我无法找出原因。我该如何纠正?
基本上,程序会生成一个从1到5的随机数,如果生成的数字低于3(1或2),则它不可用,如果3及以上,则可用。
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))
输出
Apple
Item is unavailable
Orange
Item is available
Pear
Item is unavailable
Watermelon
Item is available
The following items are unavailable
['Apple', 'Watermelon', 'Apple', 'Watermelon']
Number of fruits available = ['Orange', 'Pear', 'Orange', 'Pear']
Percentage of fruits available = 50.0
答案 0 :(得分:0)
更改此行:
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