【问题标题】:for loop prints all values but only returns one valuefor 循环打印所有值但只返回一个值
【发布时间】:2019-06-04 09:59:25
【问题描述】:

所以我有一个函数循环遍历目录中的所有文件名,打开 yaml 文件并获取两个属性,即数据库名称和集合名称。当我在函数中使用print 语句而不是return 时,这将输出所有文件名。但是,当使用return 语句时,它只会返回一个值。我真的不知道为什么我会得到这个输出并且已经尝试了很多次来弄清楚它为什么这样做。我的功能如下:

def return_yml_file_names():
    """return file names from the yaml directory"""
    collections = os.listdir('yaml/')
    collections.remove('export_config.yaml')

    for file in collections :
        with open('yaml/' + file, 'r') as f:
            doc = yaml.load(f)
            collection_name = doc["config"]["collection"]+".json"
            return collection_name

print(return_yml_file_names())

【问题讨论】:

  • 将每个值添加到列表中,然后在循环完成后返回列表。
  • 我已经尝试过了,但是这样做时它返回 None @ekhumoro
  • 那是因为你实际上并没有返回列表。
  • 或使用yield 代替return

标签: python python-2.7 return return-value


【解决方案1】:

所以你的意思是当你把return collection_name替换成print(collection_name)时,函数就可以正常工作了?

这是因为return是一个控制流语句。当代码遇到return 语句时,它会立即停止正在执行的操作并退出函数。请注意,这意味着它不会继续到 for 循环的下一次迭代。

print() 不会改变程序的流程;因此,代码会点击它,执行它,然后继续进行 for 循环的下一次迭代。

对于这个问题,我推荐

  1. 在函数开头创建一个空列表
  2. 不要将returning collection_name 添加到列表中
  3. for 循环之后,返回现在完整的列表。

代码如下所示:

def return_yml_file_names():
    """return file names from the yaml directory"""
    collections = os.listdir('yaml/')
    collections.remove('export_config.yaml')
    collection_name_list = []

    for file in collections :
        with open('yaml/' + file, 'r') as f:
            doc = yaml.load(f)
            collection_name = doc["config"]["collection"]+".json"
            collection_name_list.append(collection_name)
    return collection_name_list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多