如何用公式迭代列表?

2024-06-17 14:48:06 发布

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

我是python新手,刚开始研究它。我需要一些代码方面的帮助。我无法在我的代码上产生我需要的结果。尝试了很多方法,但还是没能成功

extra_hours = hours_worked - 40 
extra_rate = rate_of_pay * 1.5
pay_for_weeks = (rate_of_pay * 40) + (extra_rate * extra_hours)



rate_of_payy = [45,15,63,23,39]
total = []
for i in range (len(rate_of_payy)):
    pay_for_weeks = (rate_of_pay * 40) + (extra_rate * extra_hours)

    total.append(pay_for_weeks)
print(total) 

预期产量:

Paying 475.0 by direct deposit
Paying 150.0 by mailed check
Paying 745.0 by direct deposit
Paying 230.0 by mailed check
Paying 390.0 by direct deposit

Tags: of代码forbyrateextrapaytotal
1条回答
网友
1楼 · 发布于 2024-06-17 14:48:06

可以在循环中执行print语句,这样就可以打印每条语句中的每个元素

print('Paying {} by {}'.format(amount, method)

字符串的format方法允许您以优雅的方式在字符串中插入变量。看看这个guide

整个代码如下所示。我还评论了一些不当行为和错误:

extra_hours = hours_worked - 40 
extra_rate = rate_of_pay * 1.5
# This line is not necessary, you're computing it for each element inside the loop
# pay_for_weeks = (rate_of_pay * 40) + (extra_rate * extra_hours)

rate_of_pay = [45,15,63,23,39]
for r in rate_of_pay:
    # Iterating over length of a list gives it's indices, not it's values
    # pay_for_weeks = (rate_of_pay * 40) + (extra_rate * extra_hours)
    # Simply iterate directly over list elements
    pay_for_weeks = (r * 40) + (extra_rate * extra_hours)
    # Here obtain the payment method into a `method` variable.
    print('Paying {} by {}'.format(pay_for_weeks, method)

相关问题 更多 >