简体   繁体   中英

Correct way to access specific index in an iterated list of tuples in Python

I have some code which is designed to calculate tax payable (Australian) on a given figure. I have a list of tuples with the tax brackets and the applicable tax rate:

rates = [(18200,0.19),(37000,0.325),(90000,0.37),(180000,0.45),(99999999999,0.45)]

I then have a method which takes in an income amount and calculates the applicable tax.

    def calc_tax(self,income):
        tax_payable = 0
        for i,(bracket,rate) in enumerate(self.rates):
            if income >= bracket:
                amt_above_brkt  = min(income - bracket,self.rates[i+1][0] - bracket)
                tax_payable += amt_above_brkt * rate
        print(tax_payable)

The function works, it gives me the correct tax, no issues there. What I don't like is the self.rates[i+1][0] call within the function to get the upper threshold (next index) for the tax bracket.

Is there a better way to do this using the enumerated and unpacked tuple?

If you zip the upper and lower bounds together, it becomes more readable and you don't need the i any longer:

def calc_tax(income):
    tax_payable = 0
    rate_bounds, rate_list = zip(*rates)
    for rate, lo, up in zip(rate_list[:-1], 
                            rate_bounds[:-1], 
                            rate_bounds[1:]):
        if income >= lo:
            amt_above_brkt  = min(income - lo, up - lo)
            tax_payable += amt_above_brkt * rate
    print(tax_payable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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