[英]How to implement list of names into a pre-made class?
I have a class called Name that takes first and last name with few basic functions: 我有一个名为Name的类,它使用几个基本功能来使用名字和姓氏:
class Name:
def __init__(self, first, last):
self._first = first
self._last = last
def first(self):
return self._first
def last(self):
return self._last
def __repre__(self):
print("{} {}".format(self._first, self._last))
Now I need to create a function that takes a list that returns a list of Name objects. 现在,我需要创建一个接受列表的函数,该列表返回Name对象的列表。 Text_file is just a text file that has names line by line with a space between first and last name. Text_file只是一个文本文件,其名称逐行,名字和姓氏之间有一个空格。
def name_list(text_file):
with open(text_file) as f:
lines = f.read().splitlines()
for name in lines:
print(lines)
I realize I've only taken the list and returned the names in the list, not a list as Name objects. 我意识到我只接受了列表并返回了列表中的名称,而不是将列表作为Name对象。
How do I use my class to return a list of name objects? 如何使用我的班级返回名称对象列表?
def name_list(text_file):
file = open(text_file, 'r')
list = []
for line in file:
first, last = line.split()
list.append(Name(first, last))
return list
This will loop through each line, break it up on the space, create a name object, add it to the list, then return the list. 这将遍历每行,在空间上将其分解,创建一个名称对象,将其添加到列表中,然后返回列表。
Then to print it out do something like: 然后将其打印出来,例如:
list = name_list(file)
for name in list:
print('Name: {0} {1}'.format(name._first, name._last))
The simplest is just to split each line on white space. 最简单的就是在空白处分割每一行。 You've got some redundant stuff in the above: you can simply iterate on a file to go line by line in it -- no need to call readlines. 上面有一些多余的内容:您可以简单地循环访问文件以逐行访问文件-无需调用readlines。
def name_list(text_file):
names = []
with open(text_file) as f:
for line in f:
first_name, last_name in line.split(' ') # tuple unpacking
names.append(Name(first_name, last_name))
return names
Thought it might be cool to show how to do this as a one-liner in Python. 认为以Python的单行代码展示如何做到这一点可能很酷。 I understand it might be a bit less-readable to newcomers and, therefore, probably shouldn't be the accepted answer, but worth knowing: 我了解新手可能不太了解它,因此,它可能不应该被接受,但值得一提:
>>> names = [Name(*line.split()) for line in open(text_file)]
Basically, we iterate through each line in the text file, splitting on whitespace, then we use the *
-operator to unpack the values as positional arguments to the class. 基本上,我们遍历文本文件中的每一行,在空白处分割,然后使用*
运算符将值解压缩为类的位置参数。
One more possible solution: 另一种可能的解决方案:
name_objects = list()
with open(text_file) as f:
for each_line in f:
name_objects.append(Name(each_line.split()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.