试图循环随机列表并将vars作为列表

时间:2016-04-26 10:31:47

标签: python list dictionary

我试图遍历一组列表和dicts并从中提取正确的信息, 应该像:

从音乐中随机获取,如果随机是列表则打印列表,如果列表包含dict print dict

这是我在迷茫之前得到的!请帮助一个菜鸟!

import random
music = ['Band1', 'Band2', 'Band3', 'Band4']
Band1 = ['Album1']
Band2 = ['Album2']
Band3 = ['Album3']
Band4 = ['Album4']
Album1 = {
    "01": 'Track1', "02": 'Track2', "03": 'Track3', "04": 'Track4',
    "05": 'Track5', "06": 'Track6', "07": 'Track7', "08": 'Track8',
    "09": 'Track9', "10": 'Track10', "11": 'Track11'}

i = random.choice(music)
if isinstance(i, list):
    print('is instance')

3 个答案:

答案 0 :(得分:2)

我建议使用不同的数据结构:

music = { 
          "Band 1": {
                      "Album A": ["1-Track A1", "1-Track A2", "1-Track A3"],
                      "Album B": ["1-Track B1", "1-Track B2", "1-Track B3"],
                      "Album C": ["1-Track C1", "1-Track C2", "1-Track C3"]
                     },

          "Band 2": {
                      "Album A": ["2-Track A1", "2-Track A2", "2-Track A3"],
                      "Album B": ["2-Track B1", "2-Track B2", "2-Track B3"],
                      "Album C": ["2-Track C1", "2-Track C2", "2-Track C3"]
                     },

          "Band 3": {
                      "Album A": ["3-Track A1", "3-Track A2", "3-Track A3"],
                      "Album B": ["3-Track B1", "3-Track B2", "3-Track B3"],
                      "Album C": ["3-Track C1", "3-Track C2", "3-Track C3"]
                     }
         }

这是一个乐队词典(键:乐队名称),其中每个乐队都是一个包含专辑的词典(键:专辑名称),其中每个专辑都是一个包含曲目名称的列表(索引:曲目编号-1)。

然后我们可以假设我们的数据结构只包含字典,列表和字符串。我们想要一个选择随机轨道的函数,即一个字符串。

这是一种递归方法。如果需要,它也可以适用于返回它找到轨道的键和索引。它还具有任何嵌套深度,所以如果你想按国家或语言或类型等组合乐队那么没问题。

import random
def pick_track(music_collection):
    # we must pick a key and look that up if we get a dictionary
    if isinstance(music_collection, dict):
        chosen = music_collection[random.choice(list(music_collection.keys()))]
    else:
        chosen = random.choice(music_collection)

    if isinstance(chosen, str):  # it's a string, so it represents a track
        return chosen
    else:  # it's a collection (list or dict) so we have to pick something from inside it
        return pick_track(chosen)

现在我们像这样使用这种方法打印10个随机曲目:

for i in range(5):
    print(pick_track(music))

这可以输出以下示例:

1-Track C1
2-Track C3
2-Track A3
3-Track A3
2-Track B1

<强>更新

您还希望获得找到曲目的键和索引,即乐队名称,专辑名称和曲目编号?没问题,这是一个修改过的功能:

def pick_track2(music_collection):
    if isinstance(music_collection, dict):
        random_key = random.choice(list(music_collection.keys()))
    else:
        random_key = random.randrange(len(music_collection))
    chosen = music_collection[random_key]
    if isinstance(chosen, str): 
        return [random_key, chosen]
    else:
        return [random_key] + pick_track2(chosen)

它现在不会将曲目名称返回为字符串,而是返回创建拾取曲目路径的键/索引列表。你可以这样使用它:

for i in range(5):
    print("Band: '{}' - Album: '{}' - Track {}: '{}'".format(*pick_track2(music)))

示例输出:

Band: 'Band 1' - Album: 'Album C' - Track 1: '1-Track C2'
Band: 'Band 2' - Album: 'Album B' - Track 0: '2-Track B1'
Band: 'Band 1' - Album: 'Album B' - Track 0: '1-Track B1'
Band: 'Band 3' - Album: 'Album B' - Track 2: '3-Track B3'
Band: 'Band 3' - Album: 'Album B' - Track 2: '3-Track B3'

See this code running on ideone.com

答案 1 :(得分:1)

扭转您的订单并在列表中使用实际变量(而不是其名称作为字符串)应该可以帮助您入门:

Album1 = {
    "01": 'Track1', "02": 'Track2', "03": 'Track3', "04": 'Track4',
    "05": 'Track5', "06": 'Track6', "07": 'Track7', "08": 'Track8',
    "09": 'Track9', "10": 'Track10', "11": 'Track11'
}
Album2 = []
Album3 = ""
Album4 = 0
Band1 = [Album1]
Band2 = [Album2]
Band3 = [Album3]
Band4 = [Album4]
music = [Band1, Band2, Band3, Band4]

答案 2 :(得分:0)

当我调试这段代码时,我得到了&#34;我&#34;作为字符串。首先,您必须使用globals函数按名称获取变量。

此代码可以帮助您:

import random
music = ['Band1', 'Band2', 'Band3', 'Band4']
Band1 = ['Album1']
Band2 = ['Album2']
Band3 = ['Album3']
Band4 = ['Album4']
Album1 = {
    "01": 'Track1', "02": 'Track2', "03": 'Track3', "04": 'Track4',
    "05": 'Track5', "06": 'Track6', "07": 'Track7', "08": 'Track8',
    "09": 'Track9', "10": 'Track10', "11": 'Track11'}
Album2 = []
Album3 = ""
Album4 = 0

i = random.choice(music)
print i
#val =  eval(i)[0]
#print type(eval(val))

val2 = globals()[i][0]
print type(globals()[val2])