我在python中有一个方法/函数,在其中我试图获取一个返回值,然后我可以将其用作另一个函数中的变量

问题描述 投票:2回答:4

因此,我正在尝试学习Python,同时编写一些代码来帮助自己完成一些平凡的任务。所以我有一个函数,如果我使用print语句显示我所需要的东西,该函数就可以正常工作,但是当我将“ print”语句替换为“ return”时,我只会得到第一个元素在列表中,我知道它是因为“ return”导致函数退出,但是我不知道如何获取该值以返回其余元素。我尝试了很多事情,现在已经读了几个小时了:(仍然没有任何进展。目标:要读取目录中的所有“ * .common”文件,然后将它们与包含某些名称的文本文件进行比较,如果它们匹配,则返回“ * .common”文件的名称,以便我可以在另一个函数中将其用作变量。我到目前为止的代码

# This method gets the list of common files....
def get_common_files():
    path = (config_home)
    files = []

    for r, d, f in os.walk(path):
        for file in f:
            if '.common' in file:
                files.append(file)

    for f in files:
        return files

new_file = get_common_files()

def build_default_manifest():
    for line in fileinput.FileInput(new_manifest):
        for name in new_file:
            if line.strip() in name:
                print(name) # works as it should and displays all that i need
                return name  # only shows me the first element 


good_name = build_default_manifest()
print(good_name)  

我希望我已提供了我所需要的一切,但如果没有,请随时回来找我...

python
4个回答
1
投票
def build_default_manifest():
    for line in fileinput.FileInput(new_manifest):
        for name in new_file:
            if line.strip() in name:
                yield name  

good_name = build_default_manifest()
for name in good_name:

    print(name)

就像Z4层所说的,听起来像您需要一个发生器。

您可以像正常一样使用good_name中的每个元素进行函数调用。


1
投票

执行此操作时:

for f in files:
    return files

您只获得ffiles的第一个值。函数返回它,到此为止。当遇到return关键字时,该函数调用完成。

实际上,这实际上与称为生成器的稍微高级的模式非常接近。如果将return替换为yield,则您的功能应该起作用。解释它为什么起作用并不那么容易,但是this question有一些好的答案应该会有所帮助。

只是出于好奇,您是从头开始写这本书,还是从某个地方跟随一个例子?我对您与生成器模式的接近程度感到有点惊讶,这显然是无意的,并且假设您以前没有意识到它。


0
投票

也许我在这里遗漏了一些东西,但是您的for循环(for r,d ...)是否已经创建了名为“文件”的列表?所以,为什么不改变呢?

for f in files:
    return files

to

return files

哪个应该返回整个列表?


0
投票

我只获得列表中的第一个元素,我知道它是因为“ return”导致函数退出,但是我不知道如何获取该元素以返回其余元素。

我认为您已经意识到代码中的问题。

有两种可能的解决方案:

  1. 返回包含文件名的整个list

    def get_common_files():
        path = (config_home)
        files = []
    
        for r, d, f in os.walk(path):
            for file in f:
                if '.common' in file:
                    files.append(file)
    
        return files
    
  2. 在Python中使用yieldyield是与return一样使用的关键字,但函数将返回generator(生成器是迭代器,一种可迭代的迭代器,您只能迭代一次。生成器不会将所有值存储在内存中,它们会生成值)。

    def get_common_files():
        path = (config_home)
        files = []
    
        for r, d, f in os.walk(path):
            for file in f:
                if '.common' in file:
                    yield file
    
    def build_default_manifest():
        for line in fileinput.FileInput(new_manifest):
            for name in get_common_files():
                if line.strip() in name:
                    print(name) # works as it should and displays all that i need
                    return name  # only shows me the first element 
    
© www.soinside.com 2019 - 2024. All rights reserved.