如何返回类中列表的迭代

2024-09-29 22:04:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习Python的课程,我对它们有一个问题。你知道吗

我有一个包含以下行的txt文件:

3 37.5 200

6 36.9 200

9 36.6 100

12 36.6 0

当我运行下面的代码时,它只打印第一行。但是,我想检索所有行。我知道你可以用print(),但有可能返回吗?你知道吗

class Meds:

    def __init__(self, file):
        self.file = file

    def meds(self):
        for i in source.readlines():
            data_split = i.strip().split(' ')

            hour = data_split[0]
            temp = data_split[1]
            dose = data_split[2]

            return 'At {0}:00 - he had {1} temp, and took {2} mg of meds'.format(hour, temp, dose)

if __name__ == '__main__':
    source = open('meds.txt', 'r', encoding='utf8')

    a = Meds(source)
    print(a.meds())

    source.close()

我非常感谢您在这方面的帮助,如果您能提供好的,清晰的源代码来解释Python中的类,我将非常高兴。你知道吗


Tags: 文件selftxtsourcedatadeftemp课程
3条回答

readlines()返回文件中的所有行。您想改用readline()。你知道吗

您似乎在迭代source,而不是self.file。从meds()方法返回时,也只在一行上循环。也可以直接在文件对象上循环。考虑到这一点,循环函数可以如下所示:

for line in self.file:
    data_split = i.strip().split(' ')
    hour = data_split[0]
    temp = data_split[1]
    dose = data_split[2]
    yield 'At {0}:00 - he had {1} temp, and took {2} mg of meds'.format(hour, temp, dose)

在调用meds()的代码中,可以使用以下命令:

for med in a.meds():
    print(med)

要进一步阅读,请参阅文档here。你知道吗

你可以像这样重写你的代码:

class Meds:

    def __init__(self, file):
        self.file = file

    def meds(self):
        for i in self.file.readlines():
            data_split = i.strip().split(' ')

            hour = data_split[0]
            temp = data_split[1]
            dose = data_split[2]

            yield 'At {0}:00 - he had {1} temp, and took {2} mg of meds'.format(hour, temp, dose)


source = open('meds.txt', 'r', encoding='utf8')

a = Meds(source)
print(list(a.meds()))

source.close()

在本例中,您将使用生成器generator。你知道吗

你的Meds类有两个方法,一个是__init__,另一个是meds。你知道吗

所以它不是一个类,而是一个伪装的函数。你知道吗

不是每个编程问题都可以而且应该通过编写类来解决。你知道吗

def meds(path):
    with open(path) as medsfile:
        data = [tuple(float(k) for k in ln.split())
                for ln in medsfile if len(ln.strip()) > 0]
    return data

对输入数据运行此操作将返回元组列表:

In [4]: meds('meds.txt')
Out[4]: [(3.0, 37.5, 200.0), (6.0, 36.9, 200.0), (9.0, 36.6, 100.0), (12.0, 36.6, 0.0)]

相关问题 更多 >

    热门问题