1

所以我对Python中的字典有疑问。我想创建一个字典,其中将提示用户 2 个选项;更新字典或清除字典。首先让我向您展示我的代码:

def myStuff():
    food = {'Apple': 0, 'Banana': 0, 'Grapes': 0}
    choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
    if choice == str(1):
        apple = int(raw_input('How many apples do you want to add?\n>>'))
        banana = int(raw_input('How many bananas do you want to add?\n>>'))
        grapes = int(raw_input('How many grapes do you want to add?\n>>'))
        print 'Updating...'
        food['Apple'] = apple
        food['Banana'] = banana
        food['Grapes'] = grapes
        print  food
    elif choice == str(2):
        food['Apple'] = 0
        food['Banana'] = 0
        food['Grapes'] = 0
        print food
    else:
        return False

myStuff()

现在这是我想补充的:

1.用户不断更新字典的能力(也就是说如果有人输入10个苹果,字典将存储10个苹果,并再次提示用户输入他要输入的苹果数量来更新字典) . 我不太确定如何在其中实现循环。

2,用户在更新后可以清除他的字典的能力。例如:如果有人输入 10 个苹果,循环将再次询问用户是否要清除字典。

这有点像银行,有人存钱,如果账户里没有钱,就清空他们的账户。

4

4 回答 4

0
  1. 对于循环更新,也许尝试类似:

    for key in food:
        food[key] += int(raw_input('How many %s do you want to add?> ' % key) or 0)
    
  2. 您已经通过将值设置为零来清除字典。

于 2012-12-18T23:08:17.877 回答
0

如果我理解正确 - 你想反复问这个问题吗?在这种情况下,您需要做的就是放置while True:并缩进您想要重复的代码块,它将永远循环下去。您可能希望将它从raw_input(仅input在 Python 3 中)放到elif- 之后,或者,如果您创建food了一个全局变量(这样每次调用它就不会重新初始化为 0 myStuff()),您可以这样做:

while True:
  myStuff()
于 2012-12-18T23:44:55.710 回答
0

你可以这样做:

"""
in each loop check the fruit number to see if it is 0 or not.if it
is 0, then this means that you don't want to add fruit from the current 
type and skips to the nextFruit.Focus on the code and you realize the other parts.
"""    

import string

def myStuff():
    food = {'Apples': 0, 'Bananas': 0, 'Grapes': 0}
    choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
    fruit = 0
    nextFruit = 'Apples'
    while True:
        if choice == str(1):
            fruit = int(raw_input('How many ' + str.lower(nextFruit) + ' do you want to add?\n>>'))
            if fruit == 0 and nextFruit == 'Apples':
                nextFruit = 'Bananas'
                continue
            elif fruit == 0 and nextFruit == 'Bananas':
                nextFruit = 'Grapes'
                continue
            elif fruit == 0 and nextFruit == 'Grapes':
                print 'Updating...'
                print  food
                choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
            else:
                food[nextFruit] += fruit
        elif choice == str(2):
            food['Apples'] = 0
            food['Bananas'] = 0
            food['Grapes'] = 0
            print 'Updating...'
            print  food
            choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
        else:
            print "You've entered a wrong number....try again please:"
            print
            choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
于 2012-12-19T00:48:49.797 回答
0

有了你正在做的事情,创建你自己的类可能会更好。对于您希望执行的所有不同操作,您还应该具有不同的功能。IE。更新、清除、添加

class Fruit:
    Apple = 0
    Banana = 0
    Grape = 0

    def __repr__(self):
         return "You have {self.Apple} apples, {self.Banana} bananas, and {self.Grape} grapes".format(**locals())

    def update(self):
       while 1:
         choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
         if (int(choice) == 1):
            self.Add()
         elif (int(choice) == 2):
            self.Clear()
         else:
             print "Input not valid"

    def Add(self):
       self.Apple += int(raw_input('How many apples do you want to add?\n>>'))
       self.Banana += int(raw_input('How many bananas do you want to add?\n>>'))
       self.Grape += int(raw_input('How many grapes do you want to add?\n>>'))
       print self

    def Clear(self):
       self.Apple = 0
       self.Banana = 0
       self.Grape = 0
       print self

if __name__ == "__main__":
    fruit = Fruit()
    fruit.update()         

您还应该查看 usingtryexcept语句,以确保在使用错误输入时程序不会崩溃。此外,您应该添加退出命令以退出程序,否则这将永远循环。例如。如果用户输入是“退出”,则有条件通知它并且break.

于 2012-12-21T20:07:29.847 回答