【问题标题】:Simpler way to call variable defined inside one function from another function从另一个函数调用一个函数内部定义的变量的更简单方法
【发布时间】:2017-04-07 21:41:27
【问题描述】:

假设我有很多变量,而不是每次都写在()里面,有没有更简单的方法将所有变量压缩成一个单词?

def numbers():
    a = 1
    b = 2
    c = 3
    d = 4
    e = 5
    f = 6
    g = 7
    h = 8
    i = 9

    new_variable(a, b, c, d, e, f, g, h, i)


def new_variable(a, b, c, d, e, f, g, h, i):
    j = g + i
    print (j)
    new_variable_2(a, b, c, d, e, f, g, h, i)

def new_variable_2(a, b, c, d, e, f, g, h, i):
    k = g + h
    print (k)
    new_variable_3(a, b, c, d, e, f, g, h, i)

    def new_variable_3(a, b, c, d, e, f, g, h, i):
    l = h + i
    print (i)

numbers()

【问题讨论】:

  • 好的,我读了,但我不认为它回答了我的问题。我的问题是,我不想每次都输入“a”、“b”、“c”、“d”、“e”、“f”、“g”、“h”、“i”更简单,例如只需键入“字母”并使其能够调用所有变量。那么代替 new_variable(a, b, c, d, e, f, g, h, i) 可以变成 new_variable(alphabet) 吗?如果你知道怎么做,可以给我看看吗?
  • @JohnnyKang 我对我的帖子进行了编辑,这可能是您要查找的内容。 * 解压列表。

标签: python-3.x function variables


【解决方案1】:

你可以这样试试:

a, b, c, d, e, f, g, h, i = range(1,10)
alphabet = [a, b, c, d, e, f, g, h, i]

def new_variable(*alphabet):
    j = g + i
    print (j)
    new_variable_2(*alphabet)

def new_variable_2(*alphabet):
    k = g + h
    print (k)
    new_variable_3(*alphabet)

def new_variable_3(*alphabet):
    l = h + i
    print (i)

new_variable(*alphabet)

返回与您的代码相同的数字。

【讨论】:

  • 太棒了!我更像是一个视觉学习者。这帮助我充分理解了机制。非常感谢!
猜你喜欢
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
  • 2018-06-12
相关资源
最近更新 更多