Python:如何格式化循环以在字典列表中提取特定值?

时间:2018-10-06 07:30:12

标签: python python-3.x

因此,我试图从以特定格式制作的字典列表中提取信息,但是为了我的一生,我无法创建一个循环来从我所需要的确切位置提取信息,但它不会打印任何内容没有收到任何错误。这是一个示例:

class Global():
    prv_word = 'dumb'
    cur_word = 'dog'
    nxt_word = 'head'

class Animal():
    dog = [
    {'head': {'funny': [8 , 7 , 1],'dumb': [9 , 3 , 2],'poofy': [18 , 4 , 11]}},
    {'tail': {'funny': [12, 2 , 4], 'dumb': [3 , 9 , 7],'poofy':[28 , 5 , 60]}}]

dog_cur = f'Animal.{Global.cur_word}'

if hasattr(Animal, Global.cur_word):
    for list in dog_cur:
        if Global.nxt_word in list:
            adj = Global.nxt_word
            index = list.index(Global.nxt_word)
            for lis in list:
                if Global.prv_word in lis:
                    adj2 = Global.prv_word
                    index2 = lis.index(Global.prv)
                    end = dog_cur[index][adj][adj2]
                    print(end)

##### TROUBLESHOOT #####
##### This works! But how do I format the loop to generate this result? #####
(print(Animal.dog[0]['head']['dumb']))

有人可以帮助我介绍一种使该循环弹出且相关值为[9, 3, 2]的方法。 我也认为格式化的dog_cur变量不起作用...还有另一种格式化该变量的方式,使其与f'Animal.{Global.cur_word}'相同的结果吗?我相信,如果您看一下我的循环,能够看到我正在尝试从字典中的列表中拉出值。在我的实际程序中,全局值不断变化,所以这就是为什么我需要一个可以找到这些值的循环的原因。帮助将不胜感激!谢谢

3 个答案:

答案 0 :(得分:0)

为什么不把它完全放在字典里呢?

class Animals():
    animals = { 
        "dog" : {
            'head': {'funny': [8 , 7 , 1], 'dumb': [9 , 3 , 2], 'poofy': [18 , 4 , 11]},
            'tail': {'funny': [12, 2 , 4], 'dumb': [3 , 9 , 7], 'poofy': [28 , 5 , 60]}},
        "cat" : { "head": {"mysterious": [1,1,1] }}}

    @classmethod
    def gett(cls, name, part_name = None, style_name = None):
        """Provide getter on inner dict. Returns None if any key given
        is invalid. Allows to specify keys partly, to get more infos on
        inner dict"""
        if name is None:
            raise ValueError("name can not be None")

        try:
            if part_name and style_name :
                return cls.animals.get(name).get(part_name).get(style_name)
            elif part_name:
                return cls.animals.get(name).get(part_name)
            else:
                return cls.animals.get(name)
        except:
            return None

print(Animals.gett("dog","head","dumb")) 
print(Animals.gett("cat","head","mysterious"))
print(Animals.gett("donkey","whatever","yeah"))
print(Animals.gett("dog"))

输出:

[9, 3, 2]
[1, 1, 1]
None
{'head': {'funny':  [8, 7, 1], 'dumb': [9, 3, 2], 'poofy': [18, 4, 11]}, 
 'tail': {'funny': [12, 2, 4], 'dumb': [3, 9, 7], 'poofy': [28, 5, 60]}}

我不知道您是否要付出更多努力,如果可以,您可以模仿dict:请参见How to "perfectly" override a dict?

答案 1 :(得分:0)

class Global():
    prv_word = 'dumb'
    cur_word = 'dog'
    nxt_word = 'head'

class Animal():
    dog = [
    {'head': {'funny': [8 , 7 , 1],'dumb': [9 , 3 , 2],'poofy': [18 , 4 , 11]}},
    {'tail': {'funny': [12, 2 , 4], 'dumb': [3 , 9 , 7],'poofy':[28 , 5 , 60]}}]

def find():
    animal_list = getattr(Animal,Global.cur_word, None)
    if animal_list is None: return None 

    animal_part = next(filter(lambda pdct: Global.nxt_word in pdct, animal_list), None)
    if animal_part is None: return None 

    if Global.nxt_word in animal_part and Global.prv_word in animal_part[Global.nxt_word]:
        animal_part_data = animal_part[Global.nxt_word][Global.prv_word]
        return animal_part_data
    else:
        return None

print(find())

答案 2 :(得分:0)

我必须添加另一个答案,该答案以面向对象的方式使用类。这就是我要建立解决方案结构的方式。

class Selector(object):
    def __init__(self, animal="", part="", descriptor=""):
        super(Selector, self).__init__()
        self.animal = animal
        self.part = part
        self.descriptor = descriptor

current_selector = Selector("dog", "head", "dumb")

class Animal(object):
    def __init__(self, kind="", parts=[]):
        super(Animal, self).__init__()
        self.kind = kind
        self.parts = parts

    def find_part(self, part_name):
        return next(filter(lambda p: p.name == part_name, self.parts), None)

class AnimalPart(object):
    def __init__(self, name="", descriptors={}):
        super(AnimalPart, self).__init__()
        self.name = name
        self.descriptors = descriptors

    def find_descriptor(self, desc_name):
        return self.descriptors[desc_name]


animals = {}

def init():
    # create dog
    dog = Animal("dog", [   AnimalPart('head', {'funny': [8 , 7 , 1],'dumb': [9 , 3 , 2],'poofy': [18 , 4 , 11]}),
                            AnimalPart('tail', {'funny': [12, 2 , 4], 'dumb': [3 , 9 , 7],'poofy':[28 , 5 , 60]})])
    animals['dog'] = dog

def find():
    sel = current_selector
    return animals[sel.animal].find_part(sel.part).find_descriptor(sel.descriptor)

init()
print(find())