假设我有一个用户列表,其中每个元素代表另一个用户数据列表,如下所示:
users = [
["name1", 24, "address1"],
["name2", 54, "address2"],
["name3", 32, "address3"]
]
要访问第一个用户的年龄,我必须这样做:
print(users[0][1])
输出:
24
但是我想要一种方法将每个列表元素转换为用户对象,以便于访问,例如:
print(user1.age)
输出:
24
处理我的情况的最好方法是什么?我只是想要一种更简单的方法从一堆列表中访问用户数据。
您正在查找Python中的namedtuple
类型。
https://docs.python.org/3/library/collections.html
from collections import namedtuple
User = namedtuple('User', ['name','age','address'] )
users = [
# name # age # address
["name1", 24, "address1"],
["name2", 54, "address2"],
["name3", 32, "address3"]
]
users = [User(*k) for k in users]
print(users)
print(users[0].age)
输出:
[User(name='name1', age=24, address='address1'), User(name='name2', age=54, address='address2'), User(name='name3', age=32, address='address3')]
24
namedtuple
是完美的。如果您需要使用User
对象做更复杂的事情,那么dataclass
可能是下一个步骤。
from dataclasses import dataclass
users = [
["firstname1 name1", 24, "address1"],
["firstname2 name2", 54, "address2"],
["firstname3 name3", 32, "address3"]
]
@dataclass
class User:
name: str
age: int
address: str
@property
def first_name(self):
return self.name.split()[0]
user_objects = [User(*u) for u in users]
现在你可以这样做:
>>> user_objects[0].age
24
>>> user_objects[0].name
firstname1 name1
>>> user_objects[0].first_name
firstname1