【问题标题】:How to call lists from a function in the main program?如何从主程序中的函数调用列表?
【发布时间】:2016-03-04 20:00:55
【问题描述】:

我需要使用一个函数中的 2 个列表,然后调用该函数来计算这些列表的总和。如何使用函数和参数来做到这一点?

def lists():
    list1 = [150, 250, 190, 230]
    list2 = [110, 200, 125, 130]

def sumOfLists():
    sum = sum(list1) + sum(list2)
    return sum

sumOfLists()

【问题讨论】:

  • 为什么lists 是一个函数?
  • 我只能在函数中使用它们。

标签: python list function sum return


【解决方案1】:

lists 应该返回列表。 sumOfLists 应该得到 2 个列表并返回它们的总和。

def lists():
    list1 = [150, 250, 190, 230]
    list2 = [110, 200, 125, 130]
    return list1,list2


def sumOfLists(list1,list2):
    return sum(list1) + sum(list2)

print(sumOfLists(*lists()))

【讨论】:

  • 我正在尝试您的方法,但我无法将答案打印出来。我正在使用 Python 3.4.1。
  • 我将答案更改为支持 python 3.4。这是打印函数语法
【解决方案2】:

只需使 lists() 函数返回列表并在 sumOfLists() 中解压它们:

def lists():
    list1 = [150, 250, 190, 230]
    list2 = [110, 200, 125, 130]
    return list1, list2

def sumOfLists():
    list1, list2 = lists()
    return sum(list1) + sum(list2)

print sumOfLists()

输出:

1385

【讨论】:

    猜你喜欢
    • 2013-01-03
    • 2019-06-30
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    相关资源
    最近更新 更多