简体   繁体   English

如何将名称列表实现为预制类?

[英]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.

相关问题 如何读取用户的输入,搜索预先制作的字符串列表,然后在 Python 中返回匹配的内容? - How to read the user's input, searching for a pre-made list of strings, and then return the matched content in Python? 如何在项目中使用预制应用程序? - How do I use a pre-made app with my project? 如何在 tensorflow 2.0 中使用预制密集层进行训练? - How to run training with pre-made dense layers in tensorflow 2.0? 检查用户创建的列表项是否存在于预制列表中的问题 - Problem with checking if user-created list items exist in a pre-made list 如何在matplotlib中为热图使用预制的颜色贴图? - How can I use a pre-made color map for my heat map in matplotlib? Python:给定两个预制函数,如何有效选择要使用的函数? - Python: how to efficiently choose which function to use, given two pre-made functions? 使用预制用户界面 (pygubu) 时如何在 Tkinter 中扩展滚动条 - How to expand a Scrollbar in Tkinter when working with a pre-made user interface (pygubu) 为 TensorFlow 预制估计器定义输入函数 - Defining the input-function for TensorFlow pre-made estimator 1.14版中的预制估算器的推断输入函数 - input function for inference with pre-made Estimator in version 1.14 从预制列表生成 Pandas DataFrame? (“通过了 5 列,通过的数据有 500 列”) - Generate a Pandas DataFrame from Pre-made Lists? ("5 columns passed, passed data had 500 columns")
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM