【问题标题】:How to use returned value from a function如何使用函数的返回值
【发布时间】:2018-11-17 21:22:52
【问题描述】:

我有一个函数可以找到通过图形的所有路径。该函数返回所有路径的列表。以后如何在我的代码中使用这个值?

def findpaths(attachednodes,startID,endID,path = []):
    path = path + [startID]

    if startID == endID:
        return [path]

    if startID not in attachednodes:
        return []

    paths = []
    for n in attachednodes[startID]:
        if n not in path:
            newpath = findpaths(attachednodes,n,endID,path)
            for new in newpath:
                paths.append(new)

    for i in range(len(paths)):
        numflight = i
        flight = paths[i]
        flights.update({numflight: flight})

    return paths

【问题讨论】:

  • 在代码后面使用该值是什么意思?
  • 只调用函数? my_path = findpaths(nodes, start, end)
  • 请注意,作为空列表的可变对象是错误的默认值。比较 Mutable Default Arguments 下的 here

标签: python function return


【解决方案1】:

你把函数调用放在变量赋值的右边。该变量将具有返回值: 例如

def some_function():
  return 10

x = some_function()
print(x) # will print 10

【讨论】:

    猜你喜欢
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多