【发布时间】:2023-03-24 02:18:01
【问题描述】:
我有一个关于 python 'functions' 编程的问题。
这是我的脚本:
def print_seat(seat):
for item in seat:
print "${}".format(item)
print "-"*15
total = get_seat_total(seat)
print "Total: ${}".format(total)
def get_seat_total(seat):
total = 0
for dish in seat:
total += dish
return total
def main():
seats = [[19.95], [20.45 + 3.10], [7.00/2, 2.10, 21.45], [7.00/2, 2.10, 14.99]]
grand_total = 0
for seat in seats:
print_seat(seat)
grand_total += get_seat_total(seat)
print "\n"
print "="*15
print "Grand total: ${}".format(grand_total)
if __name__ == "__main__":
main()
这是我的脚本结果:
$19.95
-----------
Total: $19.95
$23.55
-----------
Total: $23.55
$3.5
$2.1
$21.45
------------
Total: $3.5
$3.5
$2.1
$14.99
------------
Total: $3.5
============
Grand total: $50.5
但是脚本的结果应该是这样的:
$19.95
-----------
Total: $19.95
$23.55
-----------
Total: $23.55
$3.5
$2.1
$21.45
------------
Total: $27.05
$3.5
$2.1
$14.99
------------
Total: $20.59
============
Grand total: $91.14
从上面可以看出,列表中的总数是不同的。我想我写的所有东西都正确,包括列表的总和(如果我没记错的话)。有人可以指出我的脚本结构有什么问题吗?还是我脚本写错了?
【问题讨论】:
-
只是一个旁注。
itertools.chain函数提供了一种对嵌套列表中元素求和的更好方法,例如sum(itertools.chain(*seats))。这是快速、实用且简洁的。 -
谢谢!!!下次写剧本的时候我会记得的!!干杯!!!
标签: python list function sum main