简体   繁体   English

如何通过基于python中匹配的属性遍历字典的键/值对来为列表中的每个项目分配新的类?

[英]How can I assign new classes to each item in a list by iterating over a dictionary's key/value pairs based on a matched attribute in python?

Every existing object in this list needs to be replaced with an instance of a specific class. 此列表中的每个现有对象都需要替换为特定类的实例。 Each existing object already has a .type which should pair with a key in a dictionary to produce the appropriate class (value in dict). 每个现有对象都已经具有.type,该类型应该与字典中的键配对以生成适当的类(dict中的值)。 Objects then also need to regain their original .name from before class assignment. 然后,对象还需要从类分配之前重新获得其原始.name。

I can't find a way to do this that doesn't involve nested for-loops, but nested for loops are basically assigning to EVERY member of a class the same name (the last name saved to a temporary variable). 我找不到一种不涉及嵌套的for循环的方法,但是嵌套的for循环基本上是为类的每个成员分配相同的名称(姓氏保存到临时变量中)。

I've dug through all of the basic literature and understand the fundamental logic surrounding loops, dictionaries, and lists, I'm just (sure that I'm) executing something improperly or nesting something the wrong way. 我已经阅读了所有基本文献,并了解了有关循环,字典和列表的基本逻辑,我只是​​(确保我)不正确地执行某些操作或以错误的方式嵌套了某些内容。

class gameObject(object):
    def __init__(self):
        self.name = name

#Class given to any living thing in the game; confers basic stats
class livingThing(gameObject):
    def __init__(self, name="Living Thing", HP = 0):
        self.name = name
        self.HP = HP
        self.alive = True
        self.safe = True
        self.listready = False

# After livingThing, classes narrow into more specific groups that have unique traits, abilities, and roles in the game

class Animal(livingThing):
    def __init__(self):
        super().__init__()
        self.truename = ""
        self.type = ""
        self.listready = False
        self.type = "Test"
        self.truetype = ""
        self.hasatype = False


class Reptile(Animal):
    def __init__(self):
        super().__init__()
        self.therm = "ecto"
        self.type = "Game Reptile"

class Amphibian(Animal):
    def __init__(self):
        super().__init__()
        self.therm = "ecto"
        self.type = "Game Amphibian"

class Bird(Animal):
    def __init__(self):
        super().__init__()
        self.therm = "endo"
        self.type = "Game Bird"

class Mammal(Animal):
    def __init__(self):
        super().__init__()
        self.therm = "endo"
        self.type = "Game Mammal"

class Fungus(Animal):
    def __init__(self):
        super().__init__()
        self.therm = "none"
        self.type = "Game Fungus"

class Fungus(Animal):
    def __init__(self):
        super().__init__()
        self.therm = "none"
        self.type = "Game Fungus"

class Ascomycetes(Animal):
    def __init__(self):
        super().__init__()
        self.therm = "none"
        self.type = "Game Ascomycetes"

somereptile = Reptile()
somereptile.type = "Reptiles"
somereptile.name = "Some Reptile"

somefrog = Amphibian()
somefrog.type = "Amphibians"
somefrog.name = "Some frog"

somefungus = Fungus()
somefungus.type = "Fungi"
somefungus.name = "Some Fungus"

secondfrog = Amphibian()
secondfrog.type = "Amphibians"
secondfrog.name = "Second Frog"

thirdfrog = Amphibian()
thirdfrog.type = "Amphibians"
thirdfrog.name = "Third Frog"

secondfungus = Fungus()
secondfungus.type = "Fungi"
secondfungus.name = "Second Fungus"

dummypop = [somereptile, somefrog, somefungus, secondfrog, thirdfrog, secondfungus]


### PROBLEM FUNCTION ###
def givetype(poplist):
    typedict = {
    "Reptiles" : Reptile(),
    "Amphibians" : Amphibian(),
    "Birds" : Bird(),
    "Mammals" : Mammal(),
    "Fungi" : Fungus(),
    "Ascomycetes" : Ascomycetes()
    }


    holderlist = []
    tempnames = []
    i = 0

    for org in poplist:
        holderlist.append(org)
        tempnames.append(org.name)
        for key in typedict.keys():
            if (holderlist[i].type.lower() in key.lower()):
                holderlist[i] = typedict[key]
                holderlist[i].name = tempnames[i]
                print(holderlist[i].name,
                                holderlist[i].type)
                        i+=1

    return holderlist


dummymaster = (givetype(dummypop))

for animal in dummymaster:
    print(animal.name, animal.type)

I expect to produce: 我希望产生:

Some Reptile Game Reptile
Some Frog Game Frog
Third Frog Game Frog
Second Frog Game Frog
etc

What I'm getting is: 我得到的是:

Some Reptile Game Reptile
Third Frog Game Frog
Third Frog Game Frog
Third Frog Game Frog
etc

Thanks for your help! 谢谢你的帮助!

You only ever create one instance of each class (which happens when you create typedict ), so all references to that instance (which is what holderlist is populated with, as opposed to distinct instances) will certainly all have the same name. 您只能为每个类创建一个实例(创建typedict时会发生这种情况),因此对该实例的所有引用(与不同实例相对应的是holderlist的填充对象)肯定都具有相同的名称。

Try not instantiating classes in typedict , and instead doing the instantiation when you need it in the for loop: 尝试不要实例化typedict类,而是在需要时在for循环中进行实例化:

typedict = {
"Reptiles" : Reptile,
"Amphibians" : Amphibian
... 
}
...

     holderlist[i] = typedict[key]()

暂无
暂无

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

相关问题 Python:迭代字典中的一些键:值对,但不是整个字典 - Python: iterating over SOME key:value pairs in a dictionary, but not the whole dictionary 如何创建嵌套字典键并从命名空间键值对列表中为其分配值? - how can I create nested dictionary keys and assign them values from a list of namespaced key value pairs? 遍历python字典中的键值对以构建对象列表 - Iterating through key value pairs in a python dictionary to build an list of objects Python:如何遍历词典列表并将每个词典作为值添加到具有唯一键的新词典中-无需重复 - Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats 如何将 CSV 读入 Python 字典,其中每个键的值都是字典列表? - How can I read a CSV into a Python dictionary, where each key's value is a list of dicts? 如何迭代多个字典键列表(值)对 - How to iterate over multiple dictionary key list(value) pairs 如果与列表中每个字典中的一个键的值匹配,则将具有不同词典值的新键添加到词典列表中 - Add new key to list of dictionaries with the values from a different dictionaries if matched with value of one key in each dictionary in a list 我怎样才能使字典中的每个键成为一个字符串,并使该键的值成为一个 Python 列表 - How can i make each key in a dictionary a string and make the value of that key a Python list 如何使用Python的pprint模块打印出嵌套在列表中的字典键值对? - How do I use Python's pprint module to pretty print out dictionary key value pairs nested with in a list? 如何展开基于键值“对”的列表的python字典? - How to unfold a python dictionary of lists based on key-value “pairs”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM