【问题标题】:how to show specific columns from a list, tabulate and print them on the console如何显示列表中的特定列,将它们制成表格并在控制台上打印
【发布时间】:2020-10-14 02:56:18
【问题描述】:

我目前正在尝试做一些密码管理器,但我被困在如何优雅地打印列表中的特定列。我可以用一种非常肮脏的方式来做到这一点,但我确信必须有一种单线的方式来管理它。 csv_file 有 3 个列:“服务”、“帐户”和“密码”。我只想以列表的方式显示满足用户输入的前两列,以模仿表格。提前感谢您的时间:)。这就是我尝试这样做的方式:

        reader = csv.DictReader(csv_file)
        service = input("PLEASE SPECIFY THE SERVICE \n ")
        header=[["service","account"]]
        for line in reader:
            if line["service"] != service:
                reader.remove(line)
        print(tabulate(([header, [el["service"], el["account"]] for el in reader]))

【问题讨论】:

    标签: python arrays python-3.x list csv


    【解决方案1】:

    经过长时间的调查,我找到了一种方法:

    service = input("PLEASE SPECIFY THE SERVICE \n")
    reader = csv.DictReader(csv_file)
    header=["service","account"]
    valid=[]
    for line in reader:
        if line["service"] != service:
            valid.append([line["service"], line["account"], line["password"]])
    print(tabulate([header, *[[line[0], line[1]] for line in valid]]))
    

    【讨论】:

      【解决方案2】:

      这个怎么样?

      reader = csv.DictReader(csv_file)
      service = input("PLEASE SPECIFY THE SERVICE \n ")
      print(tabulate(line for line in reader if line["service"] == service,
                     header=["service","account"])
      

      【讨论】:

      • 感谢您的宝贵时间。它不起作用,无法编译。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      相关资源
      最近更新 更多