添加检查列表并从Python中删除列表

时间:2016-09-01 00:17:48

标签: python list python-2.7

所以分配指令就是这个

  

打印一组简单的说明,供用户选择   钥匙开门。

所以我认为实现这一目标的目标是。

  

制作库存[彩虹键]

     

打印清单(您有这些密钥)

     

要求猜猜钥匙会打开门

     

它将检查库存,如果它是红色键,它将打印"打开"

     

否则将打印继续猜测并从库存中删除密钥

这是我到目前为止所拥有的。我还没有弄清楚如何添加和检查库存。

keepGuess = True
correctKey = "red" 

while keepGuess:
    guess = raw_input("Guess the key to open the door: ")

    if guess == correctKey:
            print ("You may enter")
            keepGuess = False
    else:

        print ("Keep guessing")

感谢您帮助我。 这是最终结果

keepGuess = True
correctKey = "blue"
keys = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

print keys
print

while keepGuess:
    guess = raw_input("Which key will open the door? ")

    if guess == correctKey:
            print ("You may enter")
            keepGuess = False
    else:
        if guess in keys != "blue":
            keys.remove(guess)
            if guess  not in keys:
                print
                print ("The key didn't open the door.")
                print ("Keep guessing")
                print
                print keys
                print

打印出来

['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

Which key will open the door? red

The key didn't open the door.
Keep guessing

['orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

Which key will open the door? red
Which key will open the door? blue
You may enter

2 个答案:

答案 0 :(得分:0)

如果没有关于错误检查的更多信息,我无法确定我是否正在解决问题。但是,我认为您想要维护一个简单的键列表,例如:

door_key_inv = ["red", "yellow", "paisley-print chartreuse"]

您将列表作为 [] (即为空)启动,并在找到密钥时添加。

现在,当用户输入猜测时,您必须进行两次检查:

  1. 这是库存中的关键颜色吗?如果是,请转到步骤2;如果没有,请打印警告。

    如果在door_key_inv中猜测:

  2. 这是正确的密钥吗?如果是这样,打开门并打破循环

  3. 循环回来进行下一次猜测。
  4. 这就是你需要的吗?

答案 1 :(得分:0)

你非常接近。您只需初始化一个空列表即可存储库存。当有人猜到一个键时,你只需将它附加到列表中即可。当然,我们会检查猜测的密钥是否已经存在于清单中,如果是,我们将不会添加它。

keepGuess = True
correctKey = "red" 
inventory = []

while keepGuess:
    guess = raw_input("Guess the key to open the door: ")

    if guess == correctKey:
            print ("You may enter")
            inventory.append(guess)
            keepGuess = False
    else:
        if guess not in inventory:
            inventory.append(guess)
        else:
            print ("You have already added this key to your inventory.")
        print ("Keep guessing")

这是一个测试:

Guess the key to open the door: blue
Keep guessing
Guess the key to open the door: blue
You have already added this key to your inventory.
Keep guessing
Guess the key to open the door: red
You may enter