简体   繁体   English

从列表设置路径的Pythonic方式

[英]Pythonic way of setting path from list

I've been trying to make a program for my brother. 我一直在努力为我哥哥制作一个节目。 One of the components of this would be to play an audio file. 其中一个组件是播放音频文件。 I have a list of about 90 audio files (please don't ask me why I have 90), and I am trying to randomly selected one and play it. 我有一个大约90个音频文件的列表(请不要问我为什么我有90个),我试图随机选择一个并播放它。 However, to play it, I have to locate its path, and then plug the path into another section of my code (which I am still in the process of fixing). 但是,要播放它,我必须找到它的路径,然后将路径插入我的代码的另一部分(我仍然在修复过程中)。 This is what I have so far: 这是我到目前为止:

import os, random

audio_playlist = [1, 2, 3, 4, ... all the way to 90]
sel_song = random.choice(audio_playlist)
song_path = None
base_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "songs")

Right now, this is how I create the path of the randomly selected song: 现在,这是我创建随机选择的歌曲的路径:

while song_path == None:
    if sel_song == 1:
        song_path = os.path.join(directory, "1.mp3")
    elif sel_song == 2:
        song_path = os.path.join(directory, "2.mp3")
# and i do this 90 times... :(

Is there a more pythonic way of doing this? 有更多的pythonic方式吗? Also, how do I make this so that setting my song's path so that I don't have to be writing hundreds of lines of code, but rather using something that's very simple and is only about 10-15 lines of code. 另外,我如何设置这个以便设置我的歌曲的路径,这样我就不必编写数百行代码,而是使用非常简单且只有大约10-15行代码的东西。 Also note that the file in song_path is basically just the number with .mp3 with it for simplicity. 另请注意, song_path中的文件基本上只是带有.mp3的数字,为简单起见。

You can directly have it as to create the path 您可以直接创建路径

if 1<= sel_song <=90:
    s.path.join(directory, "{}.mp3".format(sel_song))

And as emuiro suggested 正如emuiro所说

audio_playlist = range(1, 91)

Is also a very Pythonic way 也是一种非常Pythonic的方式

And as Padraic suggested, 正如Padraic所说,

audio_playlist = random.randint(1,91)

Is an even quicker way 是一种更快捷的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM