将 for 循环的输出存储在数组中

时间:2021-06-29 19:32:27

标签: python arrays append

我的 Python 之旅仍处于起步阶段,所以这个问题对于更高级的程序员来说可能是基础。

我想分析一堆 .wav 文件,它们都存储在同一目录中,所以我创建了一个所有文件名的列表,以便我可以获取它们的音频信号和采样率。

dirPath=r"path_to_directory"
global files
files = [f for f in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, f)) and f.endswith(".wav")]
for file_name in files:
    path_to_file= dirPath+"\\"+file_name
    audio_signal, sample_rate = sf.read(path_to_file)

sfsoundfile 库。

audio_signal 是一个数组,sample_rate 是一个数字。

现在我希望能够将 audio_signalsample_rate 与相应的 file_name 一起存储,以便我以后可以访问它们。我该怎么做?

我试过了

files = [f for f in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, f)) and f.endswith(".wav")],[]
for file_name in files[0]:
    path_to_file= dirPath+"\\"+file_name
    audio_signal, sample_rate = sf.read(path_to_file)
    files[1].append(audio_signal)
    files[2].append(sample_rate)

这似乎有效,但有没有更优雅的方法?我觉得 audio_signalsample_ratefile_name 是单独的值而不是相互依赖的。

1 个答案:

答案 0 :(得分:0)

您正在寻找的数据结构是一个关联数组,它将相关联——键是文件名和在这个例子中,值是一个由音频信号和采样率组成的元组。

关联数组的实现作为 dictionary 类型内置到 Python 中。

您可以在此处了解词典: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

您代码中的应用程序如下所示:

$36,294.89
$2,216.34
$0.002825
$0.721100
$0.267331