英文:
Creating variables from a python dictionary with multiple values for each key using a for loop
问题
我已经使用```pydub```包将音频(wav)文件导入Python。我有一个包含每个键匹配2个值的字典。键的目的是在后续步骤中用作变量名称以进行变量创建。值将用于指定切割音频文件的截止点(起始和结束时间戳)。
我想创建一个for循环,用键的名称创建多个变量,相应的值将用作切片的音频文件,其中音频文件变量被命名为"audio"(例如,audio[0:300000])。
这是我的字典示例:
```python
pairs = {
"part1": [0, 300000],
"part2": [300001, 600000],
"part3": [600001, 900000],
"part4": [900001, 1200000]
}
我已编写了以下代码,但不确定如何在for循环中动态创建包含实际切片音频文件的变量。
for key, start_end in pairs.items():
start, end = start_end
sliced_audio = audio[start:end]
其他SO帖子提到了以下内容,但我不想要字符串。我想要包含切片音频文件的实际变量。谢谢!
print(f"{key} = {sliced_audio}")
<details>
<summary>英文:</summary>
I have an audio (wav) file imported into Python using the ```pydub``` package. I have a dictionary consisting of each key matching to 2 values. The key is meant to be used as the name for the variable in a subsequent step for variable creation. The values are to be used to designate as the cut-off points to cut the audio file (start and end timestamp).
I want to create a for loop that creates multiple variables with the name of the key and the corresponding value to be the sliced audio file, with the audio file variable being named "audio" (e.g. audio[0:300000])
Here is a sample of my dictionary:
pairs = {
"part1": [0, 300000],
"part2": [300001, 600000],
"part3": [600001, 900000],
"part4": [900001, 1200000]
}
I've written the following code, but I'm unsure how to dynamically create a variable with the actual sliced audio file in a for loop.
for key, start_end in pairs.items():
start, end = start_end
sliced_audio = audio[start:end]
Other SO posts mentioned the following, but I do not want strings. I want the actual variables with the sliced audio file in them. Thanks!
print(f"{key} = {sliced_audio}")
</details>
# 答案1
**得分**: 1
请看以下中文翻译:
正如评论中所提到的,不要动态创建变量。而是创建一个新的字典:
```python
audio_parts = {}
for key, start_end in pairs.items():
start, end = start_end
sliced_audio = audio[start:end]
audio_parts[key] = sliced_audio
英文:
As in the comments, don't dynamically create variables. Instead create a new dictionary:
audio_parts = {}
for key, start_end in pairs.items():
start, end = start_end
sliced_audio = audio[start:end]
audio_parts[key] = sliced_audio
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论