python - 有没有办法清理这个结构?
问题描述
我正在练习编程,想知道是否有办法在我进行时改进我的嵌套。我知道这种结构永远不会用于严肃的项目,但是有没有办法改进我的结构?
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.')
解决方案
如果您的 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.
推荐阅读
- python - 删除日志文件后python记录丢失消息
- laravel - JSON/整数数组的 Laravel 验证不起作用
- questdb - 估计 QuestDB 的磁盘空间要求
- c# - 使用 HealthChecks 检查我的 Quartz 是否健康
- kotlin - Kotlin kmm 创建类型为:CValuesRef 的变量
- aggregate-functions - Qlikview 聚合
- sql - SQL中不同表访问两个不同字段时如何添加分隔符
- postgrest - PostgREST:禁用对除功能以外的所有内容的直接访问
- oracle - 带有减号运算符问题的 Oracle 查询
- javascript - 从flexform获取域时如何为cookie设置域