【问题标题】:Store output from for loop in an array将 for 循环的输出存储在数组中
【发布时间】:2021-09-12 00:20:11
【问题描述】:

我的 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 是单独的价值观,而不是相互依存的。

【问题讨论】:

  • 我不确定您显示的代码是否真的有效,据我所知files[2] 不存在并且应该给出错误。
  • @mkrieger1 是的,你是对的。它存在于原始代码中,但当我在这里复制时不知何故丢失了。
  • 请不要通过 \\ 添加两个字符串来构造文件名。改用os.path.join()(又名:让自己养成编写跨平台代码的习惯)
  • @umläute 感谢您的提示!

标签: python arrays append


【解决方案1】:

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

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

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

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

result = {}

for file_name in files:
    # as before:
    # ...
    audio_signal, sample_rate = ...
    # new:
    result[file_name] = audio_signal, sample_rate

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2022-08-03
    • 2020-02-27
    • 1970-01-01
    相关资源
    最近更新 更多