我有一个来自外部文本文件的字符串列表。每个字符串都是这样的:name job location
。将每个字符串变成一个对象,创建一个对象列表的最快方法是什么?
对象如下:
class Person:
def __init__(self, name, job, location):
self.name = name
self.job = job
self.location = location
答案 0 :(得分:1)
我建议逐行读取文件。 对于每一行,将其拆分为子字符串,然后是名称,工作和位置。 您可以从中创建一个人员对象并将其推入列表。
答案 1 :(得分:1)
您将需要打开文件,逐行阅读,在空格处分割行(因为您不想添加逗号)并创建对象:
p = []
with open('file', 'r') as f:
for line in f:
values = line.split(' ')
p.append(people(values[0], values[1], values[2]))
答案 2 :(得分:1)
我认为“人民”对这个班级来说是个坏名字。通常,标准命名约定表示类应以大写字母开头。同样,该类的单个实例代表一个人,而不是几个人。我认为此类最好的名称是“人”。
假设您有一个文本文件(data.txt
),如下所示:
Bob Teacher Alabama
Frasier Psychiatrist Seattle
和代码:
class Person:
def __init__(self, name, job, location):
self.name = name
self.job = job
self.location = location
def get_info(self):
return f"My name is {self.name}, and I'm a {self.job} in {self.location}."
def main():
people = []
filename = "data.txt"
with open(filename, "r") as file:
for line in file:
person = Person(*line.split())
people.append(person)
for person in people:
print(person.get_info())
return 0
if __name__ == "__main__":
from sys import exit
exit(main())
输出:
My name is Bob, and I'm a Teacher in Alabama.
My name is Frasier, and I'm a Psychiatrist in Seattle.