简体   繁体   English

从字典中删除项目,并在 0 处停止

[英]Removing items from a dictionary, and stopping at 0

My current code removes the items in the dictionary and decreases the item count by 1. But it also decreases the count after 0 (eg -1, -2)我当前的代码删除了字典中的项目并将项目计数减少了 1。但它也减少了 0 之后的计数(例如 -1、-2)

import random
item = {"HSE" : 8, "FAC" : 8, "SHP" : 8, "HWY" : 8, "BCH" : 8}
item_list = list(item)

def find_random1():                
    random_building1 = random.choice(item_list)
    item[random_building1] -= 1
    return random_building1

find_random1()   #do this a couple of times if needed

print("Building    Remaining")
print("--------    ---------")
for i in item:
    print("{:<13s}{:<d}".format(i, item[i]))

You can do find_random1() a couple of times or add a second find_random() function to speed up the subtraction of items.您可以执行 find_random1() 几次或添加第二个 find_random() 函数来加速项目的减法。 This is meant to be a random item picker.这意味着是一个随机项目选择器。 After an item is selected at random, the item count in the dictionary would decrease by 1. If the item's count is 0, it would not be picked.随机选择一个项目后,字典中的项目数将减少1。如果项目数为0,则不会被选中。 What I expect to get is the table below for the print function我期望得到的是打印功能的下表

Building    Remaining
--------    ---------
HSE          0
FAC          0
...         ...
BCH          0

How do I check if the item in the dictionary is more than 0 before selecting it at random and decreasing the value?在随机选择并减小值之前,如何检查字典中的项目是否大于 0? Any suggestions?有什么建议么? (Sorry if I sounded rude in this post) (对不起,如果我在这篇文章中听起来很粗鲁)

Just add an if condition to decrement the value only if the value is greater than 0.只需添加一个if条件,仅当值大于 0 时才递减该值。

I have tried to run the find_random1() for 10 times to show you the output.我尝试运行find_random1() 10 次以向您显示输出。

import random
item = {"HSE" : 8, "FAC" : 8, "SHP" : 8, "HWY" : 8, "BCH" : 8}
item_list = list(item)

def find_random1():                
    for i in item_list:
        random_building1 = random.choice(item_list)
        if item[random_building1] > 0:
            item[random_building1] -= 1
    return random_building1

for _ in range(10):
    find_random1()   #do this a couple of times if needed

print("Building    Remaining")
print("--------    ---------")
for i in item:
    print("{:<13s}{:<d}".format(i, item[i]))
Output:

Building    Remaining
--------    ---------
HSE          0
FAC          0
SHP          0
HWY          0
BCH          2

Your code will not execute.您的代码将不会执行。

random.choice() isn't doing what you would hope. random.choice()没有做您希望的事情。 In the first iteration of your for loop, random_building1 will contain a single character (either one of 'H', 'S' or 'E').for循环的第一次迭代中,random_building1 将包含一个字符(“H”、“S”或“E”之一)。 When you try to index the item list using that single character you will get a KeyError exception当您尝试使用该单个字符索引项目列表时,您将收到 KeyError 异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM