如何遍历包含类的多个词典。我真的不知道该怎么解释。如果您有任何疑问,请在下方留言
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")
有没有办法搜索词典列表?就像一次搜索三个中的一个,然后比较所有内容,然后如果有匹配的内容打印出来,exp?尽管我可以通过对每个字典进行编码来解决问题,但我相信有更优化,更有效的方法可以做到这一点。谢谢:D
答案 0 :(得分:0)
我很确定,您只需要创建词典的集合(列表)并在其上循环即可。像这样:
let newLabel = UILabel()
newLabel.text = "Hello There"
newLabel.font = UIFont.systemFont(ofSize: 16)
newLabel.numberOfLines = 2
newLabel.lineBreakMode = .byWordWrapping
newLabel.sizeToFit()
newLabel.frame.origin.x = 100
newLabel.frame.origin.y = 500
view.addSubview(newLabel)
如何遍历它们取决于您自己。您可以使用嵌套的for循环来做到这一点:
traits = [inte, stre, will]
如果需要,可以添加一些语法糖以节省一些缩进:
for trait in traits:
for k, v in trait.items():
# checks and prints here