【问题标题】:Sum of lists in a function函数中列表的总和
【发布时间】: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


【解决方案1】:

问题在于,在您的 get_seat_total() 函数中,您是从循环内部返回的,因此它会在仅添加第一项后返回总数。您应该只在循环完成后返回,示例 -

def get_seat_total(seat):
    total = 0
    for dish in seat:
            total += dish
    return total

【讨论】:

  • 谢谢大佬!!!它就像一个魅力! :) 现在我知道“返回”不应该在循环中,否则我只会得到第一项。 :) 我会记住这一点的!!
【解决方案2】:

希望对你有帮助,

def print_seat(seat):
    for item in seat:
            print "${}".format(item)
    print "-"*15
    total = sum(seat)
    print "Total: ${}".format(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 += sum(seat)
            print "\n"
    print "="*15
    print "Grand total: ${}".format(grand_total)

if __name__ == "__main__":
    main()

最好的,

【讨论】:

  • 或在您的脚本中,只需将 return 放在函数 get_seat_total(seat) 中的循环之外:否则它会选择列表的第一个元素,在您的情况下为 3.5。
  • 非常感谢 SuJaY!我不知道我也可以忽略定义 get_seat_total 函数,只需插入 total = sum(seat) 来解决问题!!你们都是我的救星!!再次感谢!!
  • 如果对您有帮助,请投票,因为这可以帮助我。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
相关资源
最近更新 更多