简体   繁体   English

从另一个函数调用变量

[英]Calling a variable from another function

This is a simple example of the type of problem I have run into: 这是我遇到的问题类型的一个简单示例:

def making_list(text):
    list_ = []
    i = 0
    while i < int(len(text)):
        list_.append(text[i])
        i += 1
    return list_

def calling_list(list_):
    print list_

text = raw_input("text input")

making_list(text)
calling_list(list_)

The variable list_ , which comes from making_list , is not recognized by the function calling_list . 可变list_,它来源于making_list,不被功能calling_list识别。 What is a possible solution to this problem? 有什么可能的解决方案?

Thank you 谢谢

You're not storing the variable anywhere. 您不会将变量存储在任何地方。

mylist = making_list(text)
calling_list(mylist)

Explanation: The variable names are valid only in scope of the function. 说明:变量名仅在函数范围内有效。 If you leave function (with returning some local variable), you are returning only the 'value' of the variable, not it's name, you need to assign it to variable outside. 如果离开函数(返回一些局部变量),则仅返回变量的“值”,而不是其名称,您需要将其分配给外部变量。

You have to declare the variable that will take the output of making_list as its value. 您必须声明将making_list的输出作为其值的变量。 making_list function returns list_ ; making_list函数返回list_ ; but you can not reach it if you do not assign it to another variable out of your function. 但是如果您不将其分配给函数之外的另一个变量,则无法实现。

list_ = making_list(text) will solve your problem. list_ = making_list(text)将解决您的问题。

Your making_list -function doesn't return anything. 您的making_list函数不返回任何内容。 This will work 这会起作用

list = making_list(text)
calling_list(list)

That will work. 那可行。

I don't want to change or optimize your code, I just want to give a possible solution: 我不想更改或优化您的代码,我只想提供一个可能的解决方案:

1)If you want list_ to be stored in memory, change the last 2 lines of your code like this: 1)如果您希望将list_存储在内存中,请更改代码的最后两行,如下所示:

list_=making_list(text)
calling_list(list_)

Now you can access list_ anywhere in your code. 现在,您可以在代码中的任何位置访问list_。

2)If you don't want to store list_ and you just want to print it and forget about it, delete the 2 last lines of your code and write this line instead: 2)如果您不想存储list_而只想打印它而忘了它,请删除代码的最后2行,然后写成这行:

calling_list(making_list(text))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM