更新列表中对象的值

时间:2016-11-22 17:59:57

标签: python list methods replace

我有几个列表,每个列表都包含对象。所有对象都具有值“name”和“amount”。我想要做的是创建一个更新“金额”的方法,首先通过用户输入查找列表中的项目(输入名称以查找名称)然后添加或减去用户输入值(输入值以添加/输入值以减去)。

我将如何做到这一点?

这是我到目前为止所做的事情(这是不完整的但是我可以完成的任务):

Containers = []
Lids = []
Wicks = []
Labels = []
Misc = []

    class item(object):

        #Constructor
        def __init__(self, name, amount):
            self.name = name
            self.amount = amount

        #Accessors
        def getName(self):
            return self.name

        def getAmount(self):
            return self.amount


        #Mutators
        def __str__(self):
            return "[Name: " + self.name + \
                    ", Amount: " + self.amount + \
                    "]"

        def addAmount():
            found = False
            name = input("Enter the name of a container you wish to change: ")
            addNewAmount = input("Enter the amount you wish to add: ")
            for item in Containers:
                if name in item.getName():
                    found = True
                    position = Containers.index(name)
                    print(Containers[position])
            if not found:
                print("No names match that input.")

        def subtractAmount():
            update = input("Enter a new amount to subtract: ")
            self.amount = amount - update

        def addContainer():
            name = input("Enter a name for the new container: ")
            amount = input("Enter an amount for the new container: ")
            return item(name, amount)

        def addLid():
            name = input("Enter a name for the new lid: ")
            amount = input("Enter an amount for the new lid: ")
            return item(name, amount)

        def addWick():
            name = input("Enter a name for the new wick: ")
            amount = input("Enter an amount for the new wick: ")
            return item(name, amount)

        def addLabel():
            name = input("Enter a name for the new label: ")
            amount = input("Enter an amount for the new label: ")
            return item(name, amount)

        def addMisc():
            name = input("Enter a name for the new misc item: ")
            amount = input("Enter an amount for the new misc item: ")
            return item(name, amount)

        def main():
            running = True
            while running:
                print("Enter a number to start.")
                print("1) Add new container         2) Add new lid")
                print("3) Add new wick              4) Add new label")
                print("5) Add new misc Item         6) Print Inventory")
                print("7) Add Amount from item      8) Subtract Amount from item")
                print("10) quit")
                print("11) print list")
                choice = input("> ")
                if choice == "1":
                    Containers.append(addContainer())
                elif choice == "2":
                    Lids.append(addLid())
                elif choice == "3":
                    Wicks.append(addWick())
                elif choice == "4":
                    Labels.append(addLabel())
                elif choice == "5":
                    Misc.append(addMisc())
                elif choice == "6":
                    print("<==========Containers==========>")
                    for i in Containers:
                        print(i)
                    print("<=============Lids=============>")
                    for i in Lids:
                        print(i)
                    print("<=============Wicks============>")
                    for i in Wicks:
                        print(i)
                    print("<============Labels============>")
                    for i in Labels:
                        print(i)
                    print("<==========Misc Items==========>")
                    for i in Misc:
                        print(i)
                elif choice == "7":
                    return addAmount()
                elif choice == "8":
                    return subtractAmount()
                elif choice == "10":
                    quit()
                elif choice == "11":
                    print('[%s]' % ', '.join(map(str, Containers)))
                else:
                    print("Invalid entry, please try again.")

        if __name__ == "__main__":
            main()

2 个答案:

答案 0 :(得分:0)

这可能有点混乱,但应该做的工作:

  def subtractAmount():
      containers = [Containers, Lids, Wicks, Labels, Misc]
      names = ['Containers', 'Lids', 'Wicks', 'Labels', 'Misc']
      print('Select the number of list you want to search for item')
      print('\n'.join('{}) {}'.format(str(idx), lst_name) for (idx, lst_name) in enumerate(names, 1)))
      selected = input(': ')) - 1
      item_name = input('Enter the item name you are looking for: ')
      item = None
      for value in containers[selected]:
         if value.getName().lower() == item_name.lower():
         item = value
         break
      else:
          print('No item was found with that name!')
      new_amount = input('Enter the new amount for item: ')
      item.amount = new_amount

答案 1 :(得分:0)

这里有几个问题。首先是你是否希望容器,盖子,灯芯等都是同一类型的对象(&#34; item&#34;),或者是否更有意义使用子类。假设你想让它们全部相同(&#34; item&#34;)你可以根据下面的代码调整你的方法(为了简单起见我省了很多选项)。

有几点需要注意:

  1. &#34;量&#34;需要是数字(int)才能正确地添加或减去
  2. 项目的创建是类外的功能,并将项目分配到适当的列表(容器,盖子)
  3. &#34; add_amount&#34;函数查看所有项目的所有列表以查找可能的匹配并相应地调整金额。如果盖子和容器具有相同的名称,它将修改第一个匹配。

    Containers = []
    Lids = []
    Items = [Containers, Lids]
    
    class item(object):
    
        #Constructor
        def __init__(self, name, amount):
            self.name = name
            self.amount = amount
    
        #Accessors
        def getName(self):
            return self.name
    
        def getAmount(self):
            return self.amount
    
        def __str__(self):
            return "[Name: " + self.name + \
                ", Amount: " + str(self.amount) + \
                "]"
    
    def addItem():
        global new_item
        name = input("Enter a name for the new item: ")
        amount = int(input("Enter an amount for the new item: "))
        new_item = item(name, amount)
        return new_item
    
    
    def add_amount():
        found = False
        name = input("Enter the name of the item you wish to change: ")
        add_amount = int(input("Enter the amount you wish to add: "))
        for itemList in Items:
            for item in itemList:
                if name == item.getName():
                    found = True
                    position = itemList.index(item)
                    item.amount += add_amount
                    print(itemList[position])
                if not found:
                    print("No names in match that input.")
    
    def main():
        running = True
        while running:
            print("Enter a number to start.")
            print("1) Make a container         2) Make a lid")
            print("3) add amount               4) quit")
            choice = input("> ")
            if choice == "1":
                addItem()
                print new_item.amount
                Containers.append(new_item)            
            elif choice == "2":
                addItem()
                print new_item.amount
                Lids.append(new_item)
            elif choice == "3":
                add_amount()        
            elif choice == "4":
                quit()
            else:
                print("Invalid entry, please try again.")
    
    if __name__ == "__main__":
        main()
    
相关问题