仅将信息附加到 Python 中的某些行

Only append information to certain lines in Python

我正在根据学生的出生日期计算他们的年龄并将其添加到数据中:

def display(): 
    new = []
    print("\n                      STUDENT LIST")
    print("\n   ID   |    NAME    |    SURNAME    |  SEX  |   DOB   |     COB     |    AGE    \n")

    for line in students:
        line.append(age(str(line[4])))
        new.append(line)

    for newlines in new:
        print(newlines)

问题是每次调用该函数时,它的输出都会将它附加到最后。我希望能够只追加长度为 6 的行。长度已经为 6 的行应该被忽略。

第一个运行:

第二个运行:

惰性解决方案:在 appending:

之后无条件删除超出预期长度的任何内容
for line in students:
    line.append(age(str(line[4])))
    del line[7:]  # Delete extra age if it already had one
    new.append(line)

当然,您 可以 只检查 len(line) 如果错误则不做,但是无分支代码更有趣。

for line in students:
        if len(line) == 6:  # If the line is only 6 items long
                line.append(age(str(line[4])))  # Then perform the append
        new.append(line)

只检查该行是否已经超过 6 项,如果是,则忽略它。

尝试使用 PrettyTable 库:

Python 中有一个名为“PrettyTable”的库 只需转到您的终端并“pip install prettytable”即可下载该库 转到此 link 以了解有关该库的更多信息: https://www.geeksforgeeks.org/creating-tables-with-prettytable-library-python/

我喜欢这个库,因为它非常易于使用并且代码非常易读

第二天早上看了一下,才明白问题所在。我注意到 Omnikar 做出了类似的回答。非常感谢大家!

for line in test:
        if len(line) == 6:   # if the length is 6 append the lines
            line.append(age(str(line[4])))    # adding ages to list of all students
            new.append(line) 
        else:
            new.append(line)  # new lines in test that havent gotten the age conversion