[英]Python List comprehension - returned tuples seem to change when they are iterated and printed
[英]Correct way to access specific index in an iterated list of tuples in Python
我有一些代碼旨在計算給定數字的應付稅款(澳大利亞)。 我有一個包含稅級和適用稅率的元組列表:
rates = [(18200,0.19),(37000,0.325),(90000,0.37),(180000,0.45),(99999999999,0.45)]
然后我有一種方法可以計算收入金額並計算適用的稅款。
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)
function 有效,它給了我正確的稅,沒有問題。 我不喜歡 function 中的self.rates[i+1][0]
調用來獲取稅級的上限(下一個索引)。
有沒有更好的方法使用枚舉和解包的元組來做到這一點?
如果您將 zip 上限和下限放在一起,它變得更具可讀性並且您不再需要i
:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.