python - 返回字符串列表的 python 函数有问题吗?

标签 python list function python-2.7 return

我的目录中有一组文件。因此,我创建了一个函数,对目录中的所有文件进行一些处理:

def fancy_function(directory, regex):
    for set the path of the directory:
       with open the file names and walk over them:
           preprocessing1 = [....]
           preprocessing2 = [ remove some punctuation from preprocessing1]

           return preprocessing2

然后我执行以下操作:

list_of_lists = fancy_function(a_directory, a_regex)
print list_of_lists
>>>['processed string']

它只返回一个列表,目录实际上有 5 个文件,然后当我执行以下操作时:

def fancy_function(directory, regex):
    do preprocessing...
    preprocessing1 = [....]
    preprocessing2 = [ remove some punctuation from preprocessing1]
    print preprocessing2

打印 fancy_function(a_directory, a_regex)

它返回我想要的 5 个预处理文件,如下所示:

['file one']
['file two']
['file three']
['file four']
['file five']

为什么会发生这种情况以及如何获取列表中的 5 个文件?我想将它们保存在一个列表中以便进行其他处理,但现在对于主列表中的每个列表,如下所示:

main_list =[['file one'], ['file two'], ['file three'], ['file four'], ['file five']]

最佳答案

for 循环中有一个 return 语句,这是一个常见的问题。该函数立即结束,返回单个元素,而不是返回所有已处理元素的列表。

你有两个选择。 首先,您可以在函数中显式定义一个列表,将中间结果附加到该列表,并在末尾返回该列表。

def fancy_function(directory, regex):
    preprocessed_list = []
    for set the path of the directory:
        with open the file names and walk over them:
            preprocessing1 = [....]
            preprocessing2 = [ remove some punctuation from preprocessing1]

            preprocessed_list.append(preprocessing2)
    return preprocessed_list

或者更奇特的是,你可以将你的函数变成 generator .

def fancy_function(directory, regex):
    preprocessed_list = []
    for set the path of the directory:
        with open the file names and walk over them:
            preprocessing1 = [....]
            preprocessing2 = [ remove some punctuation from preprocessing1]

            yield preprocessing2 # notice yield, not return

然后可以使用该生成器:

>>> preprocessed = fancy_function(a_directory, a_regex)
>>> print list(preprocessed)
[['file one'], ['file two'], ['file three'], ['file four'], ['file five']]

关于python - 返回字符串列表的 python 函数有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27737279/

相关文章:

python - 使用类定义的计算对列表进行排序

python - bson.objectid.ObjectId 和 bson.ObjectId 的区别?

python - 从列表列表构建字典并维护元素的位置

c - 使用数组打印出一些星号,这取决于用户在 C 中输入的数字

python - matplotlib 程序运行时窗口无响应

python - Sklearn 如何使用 Joblib 或 Pickle 保存从管道和 GridSearchCV 创建的模型?

python : compare lists of a list by length and create new lists of equal sizes

list - 如何在 Scala 中将列表元组展平为列表列表

c - 求数组对角线总和时出错

更改 HTML 的 JavaScript 函数不起作用