【问题标题】:Updating key values in dictionaries更新字典中的键值
【发布时间】:2021-07-28 06:25:00
【问题描述】:

我正在尝试为以下内容编写代码: 这个想法是有一个存储/库存字典,然后通过某些家庭任务减少键值。例如。清洁、烹饪等。

这将是存储字典:

cupboard= {"cookies":30,
    "coffee":3, 
    "washingpowder": 5,
    "cleaningspray": 5,
    'Pasta': 0.5,
    'Tomato': 4, 
    'Beef': 2, 
    'Potato': 2, 
    'Flour': 0.2, 
    'Milk': 1, 
    "Burger buns": 6}

现在这是我编写的代码,用于尝试减少一个键的值(想法是“清洁”动作将“清洁喷雾”键减少一个清洁单位 = 0.5

cleaning_amount = 0.5
def cleaning(room):
    while cupboard["cleaningspray"] <0.5:
        cleaned = {key: cupboard.get(key) - cleaning_amount for key in cupboard}
        return cupboard
    
livingroom = 1*cleaning_amount

cleaning(livingroom)
        
print(cupboard)

但它返回的是 this,它与以前的字典相同,没有更新值

{'cookies': 30, 'coffee': 3, 'washingpowder': 5, 'cleaningspray': 5, 'Pasta': 0.5, 'Tomato': 4, 'Beef': 2, 'Potato': 2, 'Flour': 0.2, 'Milk': 1, 'Burger buns': 6}

有人可以帮忙吗?

谢谢!!

附上图片以查看缩进等。

【问题讨论】:

  • while 循环中的 return 语句实际上只是 if 语句中的 return 语句。函数的执行在 return 语句之后停止。

标签: python function dictionary key key-value


【解决方案1】:

所以我相信值不变的原因是因为它是在 for 循环中完成的。

例如

list_values = [1, 2, 3, 4, 5]

new_variable = [num + 1 for num in list_values]

print("list_values", list_values) # The original list_values variable doesn't change
print("new_variable", new_variable) # This new variable holds the required value

这会返回:

list_values [1, 2, 3, 4, 5] 
new_variable [2, 3, 4, 5, 6]

所以要解决这个问题,你可以使用'new_variable'

所以,既然概念很清楚(我希望),在你的情况下,它会是这样的

def cleaning():
    while cupboard["cleaningspray"] > 0.5: # Also here, i beleive you intend to have `>` 
                                                   #and not `<` in the original code
        cleaned = {key: cupboard.get(key) - cleaning_amount for key in cupboard} 
        return cleaned

我们返回 cleaned 的“new_variable” 因此,如果需要,可以将其分配给原始字典变量,如下所示: cupboard = cleaning()

编辑: 此外,正如@d-k-bo 评论的那样,如果您打算只执行一次操作...... if 语句也可以完成这项工作

if cupboard["cleaningspray"] &gt; 0.5: # Again assuming you intended '&gt;' and not '&lt;'

否则,您应该将 return 语句保留在 while 循环之外

【讨论】:

  • 您好,首先非常感谢您!!但是我如何只访问一个键?我只希望一个键减少 0.5,而不是全部。 :)
  • @Alexa Sievers cupboard['required_key'] = cupboard['required_key'] - cleaning amount 如果橱柜是全局变量,这应该可以工作
【解决方案2】:

我猜您想根据房间大小(或其他因素)减少“清洁喷雾”的用量。我会这样做:

cleaning_amount = 0.5


def cleaning(cleaning_factor):
    if cupboard["cleaningspray"] > 0.5:
        # reduce the amount of cleaning spray depending on the cleaning_factor and the global cleaning_amount
        cupboard["cleaningspray"] -= cleaning_factor * cleaning_amount


livingroom_cleaning_factor = 1

cleaning(livingroom_cleaning_factor)

print(cupboard)

输出:

{'cookies': 30, 'coffee': 3, 'washingpowder': 5, 'cleaningspray': 4.5, 'Pasta': 0.5, 'Tomato': 4, 'Beef': 2, 'Potato': 2, 'Flour': 0.2, 'Milk': 1, 'Burger buns': 6}

【讨论】:

    猜你喜欢
    • 2013-11-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2019-07-15
    • 2021-09-04
    • 2018-11-11
    • 2017-04-25
    • 2021-03-15
    相关资源
    最近更新 更多