首页 > 解决方案 > 有没有办法清理这个结构?

问题描述

我正在练习编程,想知道是否有办法在我进行时改进我的嵌套。我知道这种结构永远不会用于严肃的项目,但是有没有办法改进我的结构?

Johnny = {
    'first': 'john',
    'last': 'doe',
    'age': '20',
    'location': 'new york city',
}

Bob = {
    'first': 'robert',
    'last': 'johnson',
    'age': '28',
    'location': 'san francisco',
}

Jenny = {
    'first': 'jennifer',
    'last': 'lopez',
    'age': '40',
    'location': 'miami',
}

people = [Johnny, Bob, Jenny]

for name in people:
    print('This is ' + name['first'].title() + ' ' + name['last'].title() +
          '. They moved to ' + name['location'].title() + ' when they were ' + name['age'] + ' years old.')

标签: pythondata-structures

解决方案


如果您的 dicts 相同,您也可以使用 python 类。这是一个例子:

class Person:
    def __init__(self, person_dict):
        self.person_dict = person_dict

    def get_person_data(self):
        return f'This is {self.person_dict["first"].title()} {self.person_dict["last"].title()}. ' \
            f'They moved to {self.person_dict["location"].title()} when they were {self.person_dict["age"]} years old.'


johnny = Person(Johnny)

print(johnny.get_person_data())

输出:

This is John Doe. They moved to New York City when they were 20 years old.

推荐阅读