循环遍历包含类的多个字典

2024-05-04 11:54:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在包含类的多个字典上循环。我真的不知道该怎么解释。如果你有任何问题,请在下面留言

class Stats:
def __init__(self, **kwargs):
    self.__dict__.update(kwargs)

inte = {1: Stats(name='Programming', exp=0, description="This is a description"),
        2: Stats(name='Reading', exp=0, description='Reading Description'),
        3: Stats(name='Meditating', exp=0, description='Meditaing Description')}

stre = {1: Stats(name='Excercise', exp=0, description="This is a description"),
        2: Stats(name='Gym', exp=0, description="Gym description")}

will = {1: Stats(name='Resistance', exp=0, description="This is a description"),
        2: Stats(name='Chores', exp=0, description='Chores description')}

# Works with every single dictionary but how to do it with multiple?
for k, v in stre.items():
    if v.name == "Excercise"
    print("You did excercise")

有没有一种方法可以搜索字典列表?就像一次搜索其中三个,然后比较所有内容,然后如果有匹配的打印在那里?虽然我可以通过编写每一本字典来四处奔波,但我相信有更优化、更有效的方法来做到这一点。谢谢:D


Tags: nameself字典isstatswithdescriptionthis
1条回答
网友
1楼 · 发布于 2024-05-04 11:54:30

我非常肯定,您只需要创建一个字典集合(列表)并循环使用它。像这样:

traits = [inte, stre, will]

你如何在他们身上循环是由你决定的。可以使用嵌套for循环执行此操作:

for trait in traits:
  for k, v in trait.items():
    # checks and prints here

如果需要,可以添加一些语法糖以节省缩进:

for k, v in [trait.items() for trait in traits]:
  # checks and prints here

相关问题 更多 >