简体   繁体   English

字典值在for循环分配中未更改

[英]Dictionary value is not changed inside a for loop assignment

So I am learning python using Learn python the hard way. 所以我正在用学习python的困难方式学习python。 I am trying to develop a inventory system. 我正在尝试开发一个库存系统。 The goal is to build this into a class that will be pulled by the room class. 我们的目标是将其构建为将由会议室类吸引的类。 I am going to use a dictionary for the inventory so that when I create the inventory for each room I can say where they are in the room. 我将使用字典的清单,以便在为每个房间创建清单时可以说出它们在房间中的位置。

So in the bedroom I can say that there is a knife on the bed rather than just saying you see knife, candle, oil. 因此,在卧室里,我可以说床上有一把刀,而不仅仅是说看到刀,蜡烛和油。

Right now I am working on picking up the item when someone says take knife. 现在,当有人说要拿刀时,我正在捡拾物品。 I am able to do a weird search and set that value to None so that when someone looks in the room it does not show up but I seem to be running into a scope issue. 我能够进行一个奇怪的搜索并将该值设置为None,这样当有人在房间里看时它不会出现,但我似乎遇到了范围问题。 I read multiple other questions on this site that said since its a mutable object i don't need to do Global dict and when i tried that it got an error. 我在该站点上阅读了多个其他问题,这些问题说,因为它是易变的对象,所以我不需要做Global dict,而当我尝试它时就遇到了错误。 I am able to edit the object but when i go back out of my if statement and for loop it won't carry over. 我可以编辑对象,但是当我退出if语句和for循环时,它将不会继续执行。

Please help me :) 请帮我 :)

#This is the inventory in this room
inventory = {'desk': 'Miniature Fusion Warhead',  
         'bed':'knife', 'sink':None}        
def take(item):
    if item in inventory.itervalues():
        #add_item_to_inventory(item)

        for key, value in inventory.iteritems():

            if value == item:
                print ("Wow.\n"
                    "Look at you.\n"
                    "Picking shit up and everything.")
                value = None


    else:
        print ("What do you think this is?"
            "  The dollar store?  We don't "
            "got that shit here!")


# Prints out what items are in the room.  
# I am hoping to later come up with an idea for how
# To make different variations of this, and have it randomly
# pick between the different ways it says what it sees.
for key, value in inventory.iteritems():
    if value != None:
        print "You see a %s on the %s." % (value, key)
print "What do you want to pick up?"
ui = raw_input(">")
split_ui = ui.split()
print split_ui

if len(split_ui) > 1:
    if split_ui[0] == "take":
        print ("You reach over to grab the %s."
            "\n...") % split_ui[1]
    take(split_ui[1])

    else:
        print ("What you talking bout Willis?  "
            "Don't you know this is just about "
            "takin shit.")
else:
    print ("Who taught you how to talk?"
        "\n...\nLet me show you how its done.\n"
        "Use a verb, like take, then throw in an "
        "object like knife.")

print inventory

This is the output that I am given. 这是我得到的输出。

You see a knife on the bed.
You see a Miniature Fusion Warhead on the desk.
What do you want to pick up?
>take knife
['take', 'knife']
You reach over to grab the knife.
...
Wow.
Look at you.
Picking shit up and everything.
{'sink': None, 'bed': 'knife', 'desk': 'Miniature Fusion Warhead'}

Important note: This currently only works if you take the knife and not the Warhead. 重要说明:目前,这仅在您拿着刀而非弹头的情况下有效。 I need to figure out another solution for items with multiple words. 我需要找出针对多个单词的项目的另一种解决方案。

Thanks! 谢谢!

The value inside your loop is different than the real value of the dictionary. value的循环内比字典的实际价值不同。 It is just a reference to that value, so when you do value = None you actually change the value of the reference to hold the new value None and not the value of the dictionary. 它只是对该值的引用,因此当您执行value = None您实际上会更改该引用的值以保留新值None而不是字典的值。

To demonstrate it better this is before the assignment inside the for key, value in inventory.iteritems(): 为了更好地说明这一点,这是for key, value in inventory.iteritems():for key, value in inventory.iteritems():赋值之前for key, value in inventory.iteritems():

-------            -------------------------
|value|   -------> |value of the dictionary|
-------            -------------------------

this is after value = None 这是在value = None

                   -------------------------
                   |value of the dictionary|
                   -------------------------
-------            ------
|value|   -------> |None|
-------            ------

As you can see the dictionary value does not change. 如您所见,字典值不会改变。 Only the variable value of the for loop changes. for循环的变量value更改。 This variable belongs to the scope of the for loop and after that it is discarded. 此变量属于for循环的范围,之后将其丢弃。

An alternative would be instead of value = None to do: 另一种选择是代替value = None来做:

inventory[key] = None

zbs is correct, you're only changing the value of the pointer to the dict value. zbs是正确的,您只是将指针的值更改为dict值。 However, you're making this way too hard: 但是,您使这种方式变得太难了:

#This is the inventory in this room
inventory = {'Miniature Fusion Warhead': 'desk',
             'knife':'bed'}
player_inventory = set()

def take(item):
  if item in inventory:
    print("You picked up the {}".format(item))
    player_inventory.add(item)
    del inventory[item]

  else:
    print("That item doesn't exist")

while True:
  print('')
  print("Inventory: " + ', '.join(player_inventory))
  for k,v in inventory.items():
    print("You see a {} on the {}".format(k, v))

  print("What do you want to pick up?")
  ui = raw_input("> ").split()
  verb = ui[0]
  item = ' '.join(ui[1:])
  if verb == 'take':
    if item:
      print("You take the {}".format(item))
      take(item)
    else:
      print("That item doesn't exist")
  else:
    print("That's not an action")

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

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