如何对集合列表求和?在类中使用字符串和整数?

2024-05-23 19:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python编程新手,正在学习python 4课程。为此,我需要建立一个预算应用程序。具体而言,这是前两项任务:

在budget.py中完成类别类。它应该能够根据不同的预算类别(如食品、服装和娱乐)实例化对象。创建对象时,将以类别的名称传递对象。该类应该有一个名为ledger的实例变量,它是一个列表。该类还应包含以下方法:

接受金额和描述的存款方法。如果没有给出描述,则默认为空字符串。该方法应以{“金额”:金额,“说明”:说明}的形式将对象附加到分类帐列表中

一种类似于存款法的提取方法,但传入的金额应作为负数存储在分类账中。如果没有足够的资金,则不应在分类账中添加任何内容。如果提取发生,此方法应返回True,否则返回False

我目前的尝试如下:

class Category:
    def __init__(self):
        self.ledger = []
        Total = 0

    def deposit(self, amount, *description):
        self.ledger.append({"amount": amount, "description": description})
              
        return self.ledger

    def withdraw(self, withdrawal):
        
        for x in self.ledger:
            if x == int():
                return sum
            
        self.ledger.append({"withdrawal": withdrawal})
        
        return self.ledger

我想我有很多问题:

  1. 什么是以{}为一项的列表?是5.4吗"Set"
  2. 我现在如何实现提取方法“如果没有足够的资金,则不应向分类账添加任何内容”的要求。我认为我需要将列表self.ledger的所有整数相加,但idk如何从中提取并相加。我尝试了一个for循环,但我认为这是不正确的语法

我真的很感谢每一个帮助,也很感谢一些背景知识

提前谢谢! 卢卡斯


Tags: 对象实例方法self列表returndefdescription
2条回答

所以,有些事情需要澄清

  1. self.ledger = [][]使分类账成为一个列表,self.部分使其成为一个实例变量,仅适用于类类别的特定实例
  2. 如评论中所述,{"key": "value"}是一个dict对象。使用self.ledger.append({"key": "value"})将dict对象{"key": "value"}添加到分类账列表中
  3. 通常,如果要跟踪类中的数字,可以创建一个实例变量,并在其发生更改时进行更新。请参阅下面self.total的用法
  4. 也可以重新计算总数,请参见下面的方法update_total()

我在下面添加了一些测试

class Category:
    def __init__(self):
        self.ledger = []
        # total also needs the "self." to make it an instance variable, just
        # as the ledger above
        # if you omit the "self."" it's a localized variable only available
        # to the __init__ method itself.
        self.total = 0

    def deposit(self, amount, *description):
        self.ledger.append({"amount": amount, "description": description})
        # add the amount to the total
        self.total += amount
        return self.ledger

    def withdraw(self, withdrawal):
        # make the withdrawal negative
        if abs(withdrawal) == withdrawal:
            withdrawal = 0 - withdrawal
        # check if there's enough in the total
        if abs(withdrawal) <= self.total:
            # update the total
            self.total += withdrawal
            # add to the ledger
            self.ledger.append({"withdrawal": withdrawal})
        else:
            # you could return an error message here
            pass
        return self.ledger

    def update_total(self):
        total = 0
        for item in self.ledger:
            # need to check if the amount key is in the dict object
            if "amount" in item:
                total += item["amount"]
            # this check below is not needed but it ensures future compatability
            elif "withdrawal" in item:
                total += item["withdrawal"]
        # just because, you can check if the totals match
        if self.total != total:
            print(
                f"""Difference in totals found. Someone is cheating :-|
  Instance total:   {self.total}
  Calculated total: {total}"""
            )
        # set the instance variable to the local variable
        self.total = total
        return self.total



from pprint import pprint
nr1 = Category()
nr2 = Category()

for i in range(10):
    nr1.deposit(i, f"deposit - {i}")

pprint(nr1.ledger)
print(f"Total: {nr1.total}")
nr1.withdraw(10)
print(f"Total: {nr1.total}")
nr1.withdraw(-10)
print(f"Total: {nr1.total}")
nr1.withdraw(99999)
print(f"Total: {nr1.total}")
pprint(nr1.ledger)
print(nr1.update_total())
nr1.total = 123
print(nr1.update_total())

# just to show that the above only updated the values inside the nr1 instance.
print(f"Total for nr2: {nr2.total}")
  1. {}是空的dict。空集是set()

  2. 对于提取功能,应该这样做:

     def withdraw(self, amount, description):
    
         balance = sum(transaction["amount"] for transaction in self.ledger)
    
         if balance >= withdrawal :
             self.ledger.append({"amount": -amount, "description": description})
             return True
         else :
             return False
    
     return self.ledger
    

这将使用生成器作为内置和函数的参数。如果您刚刚开始使用python,这可能有点高级,因此您还可以使用更为初学者友好的代码来计算平衡:

    balance = 0
    for transaction in ledger:
        balance = balance + transaction["amount"]
        # you can shorten the line above to
        # balance += transaction["amount"]

这大致相当于sum和生成器语法的作用

出于好奇,您的deposit函数中description参数前面的*是一个输入错误吗

相关问题 更多 >