Python 有没有办法为for循环的每次迭代自动生成一个空数组?

Python 有没有办法为for循环的每次迭代自动生成一个空数组?,python,pandas,scipy,librosa,Python,Pandas,Scipy,Librosa,我试图为for循环的每个过程创建一个单独的数组,以便存储wavefile.read函数生成的“信号”值 关于代码如何工作/我希望它如何工作的一些背景: 我有以下文件路径: Root directory Labeled directory Irrelevant multiple directories Multiple .wav files stored in these subdirectories Labeled directory

我试图为for循环的每个过程创建一个单独的数组,以便存储wavefile.read函数生成的“信号”值

关于代码如何工作/我希望它如何工作的一些背景:

我有以下文件路径:

Root directory 
    Labeled directory
        Irrelevant multiple directories
            Multiple .wav files stored in these subdirectories

    Labeled directory
        Irrelevant multiple directories
            Multiple .wav files stored in these subdirectories
现在,对于每个带标签的文件夹,我想创建一个数组,该数组保存其各自子目录中包含的所有.wav文件的值

这就是我所尝试的:

for label in df.index:

    for path, directories, files in os.walk('voxceleb1/wav_dev_files/' + label):
        for file in files:
            if file.endswith('.wav'):
                count = count + 1
                rate,signal = wavfile.read(os.path.join(path, file))

print(count)

上面是数据帧df的快照

最终,使用这些数组的原因是,我想计算每个标记子目录中包含的wav文件的平均时间长度,并将其作为列向量添加到数据帧中


请注意,dataframe的索引对应于目录名。我感谢所有的帮助

您发布的代码片段可以稍微简化和现代化。以下是我的想法:

我有以下目录结构:

在我的示例中,我使用文本文件而不是wav文件,因为我手头没有任何wav文件。 在我的
root
中,我有
A
B
(它们应该是您的“标记目录”)<代码>A有两个文本文件
B
有一个即时文本文件和一个子文件夹,其中包含另一个文本文件(这是为了模拟“不相关的多个目录”)

守则:

def main():

    from pathlib import Path

    root_path = Path("./root/")
    labeled_directories = [path for path in root_path.iterdir() if path.is_dir()]

    txt_path_lists = []

    # Generate lists of txt paths
    for labeled_directory in labeled_directories:
        txt_path_list = list(labeled_directory.glob("**/*.txt"))
        txt_path_lists.append(txt_path_list)

    # Print the lists of txt paths
    for txt_path_list in txt_path_lists:
        print(txt_path_list)

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())
输出:

[WindowsPath('root/A/a_one.txt'), WindowsPath('root/A/a_two.txt')]
[WindowsPath('root/B/b_one.txt'), WindowsPath('root/B/asdasdasd/b_two.txt')]

如您所见,我们生成了两个文本文件路径列表,每个标记的目录对应一个。我使用的glob模式(
***.txt
)处理多个嵌套目录,并递归查找所有文本文件。您所要做的就是更改glob模式中的扩展名,让它找到.wav文件。

我不完全理解您的意图,但我怀疑您最好在列表或字典中收集文件值,而不是在numpy数组中。空列表是
[]
,列表附加是向列表添加对象的有效方法。