繁体   English   中英

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

[英]Python: How do I format a loop to pull specific values in a dictionary list?

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

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}'结果f'Animal.{Global.cur_word}'我相信,如果您看一下我的循环,您会发现能够看到我正在尝试从字典中的列表中提取值。 在我的实际程序中,全局值不断变化,所以这就是为什么我需要一个可以找到这些值的循环的原因。 帮助将不胜感激! 谢谢

为什么不将其完全纳入命令呢?

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 :请参阅如何“完美”地覆盖dict?

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())

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

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())

暂无
暂无

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

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