从Python字典中使用for循环创建具有多个值的变量。

huangapple go评论55阅读模式
英文:

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 &quot;audio&quot; (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&#39;ve written the following code, but I&#39;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

huangapple
  • 本文由 发表于 2023年6月9日 12:38:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定