简体   繁体   English

如果值存在而没有 if else

[英]if value exists without if else

This is my django model.这是我的 django model。

class AccountTransactions(models.Model):
  amount = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True)

  @property
  def transaction_check(self):
      #what i want to do
      #If amount>0 :
           credit = amount
           debit = 0
      else;
           debit = amount
           credit = 0
      return credit, debit

How to write this if else in one line.如何在一行中写这个 if else。

There is no ternary operator in Python, you can use a few methods. Python中没有三元运算符,可以使用几种方法。 You can also use more simpler method:您还可以使用更简单的方法:

@property
def transaction_check(self):
    return ((amount, 0), (0, amount))[0 < amount]

Maybe you can use different way to use map:也许您可以使用不同的方式来使用 map:

@property
def transaction_check(self):
    return {True: (amount, 0), False: (0, amount)}[0 < amount]

Also you can use lambda expression for the result:您也可以使用 lambda 表达式作为结果:

@property
def transaction_check(self):
    return ((lambda: (amount, 0), lambda: (0, amount))[0 < amount]())

Billions different methods can be apply.可以应用数十亿种不同的方法。

You can use a conditional expression with tuple assignment:您可以将条件表达式与元组赋值结合使用:

credit, debit = (amount, 0) if amount > 0 else (0, amount)

An alternative syntax to @Barmar's answer with no (visible) if/else: @Barmar 的答案的另一种语法,没有(可见的)if/else:

class AccountTransactions(models.Model):
    amount = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True)

    @property
    def transaction_check(self):
          return max(0, amount), min(amount, 0)

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

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