【问题标题】:Only append information to certain lines in Python [duplicate]仅将信息附加到 Python 中的某些行 [重复]
【发布时间】:2021-06-28 00:02:01
【问题描述】:

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

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)

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

第一次运行:

第二次运行:

【问题讨论】:

    标签: python python-3.x list append


    【解决方案1】:

    懒惰的解决方案:在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),如果错误则不要执行此工作,但无分支代码更有趣。

    【讨论】:

      【解决方案2】:
      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 个项目,如果是,则忽略它。

      【讨论】:

        【解决方案3】:

        尝试使用 PrettyTable 库:

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

        我喜欢这个库,因为它很容易使用并且代码可读性很好

        【讨论】:

          【解决方案4】:

          第二天早上看了之后,我发现了问题所在。我注意到 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
          

          【讨论】:

          • 你为什么重复 Omnikar 的回答?
          猜你喜欢
          • 2016-01-29
          • 2013-12-20
          • 1970-01-01
          • 1970-01-01
          • 2022-01-18
          • 2016-05-01
          • 2013-11-19
          • 1970-01-01
          相关资源
          最近更新 更多