【问题标题】:Is it possible to print columnized output with os.listdir()?是否可以使用 os.listdir() 打印列输出?
【发布时间】:2017-05-25 12:36:18
【问题描述】:

我希望使用 os.listdir 创建两列。代码是标准的listdir()。

for f in os.listdir(os.curdir):
                print f

输出如下:

file1
file2
file3
file4

但我正在努力实现:

file1    file3
file2    file4

使用 os.listdir() 可以(轻松)实现吗?

【问题讨论】:

    标签: python python-2.7 listdir


    【解决方案1】:

    os.listdir 只是返回一个列表,不会像ls -C2 那样很好地打印它(请注意,如果您的系统中有ls,则不需要python)

    你可以对 2 列这样做:

    import os,itertools
    
    dl=os.listdir(".")
    
    for t in itertools.zip_longest(dl[::2],dl[1::2],fillvalue=""):
        print("{:<20} {:<20}".format(*t))
    

    这会将值交错在一起(使用zip_longest 以避免忘记一个奇数)并为每个值使用 20 个空格进行格式化。

    任意数量的列的一般情况可能是:

    import os,itertools
    
    dl=os.listdir(".")
    
    ncols = 3
    
    for t in itertools.zip_longest(*(dl[i::ncols] for i in range(ncols)),fillvalue=""):
        print(("{:<20}"*ncols).format(*t))
    

    (生成ncols移位列表,将它们交错,并相应地生成格式)

    【讨论】:

      【解决方案2】:

      不,os.listdir() 不可能。您可能需要考虑其他选项,例如 How to print a list more nicely?

      【讨论】:

        【解决方案3】:

        您可以使用来自此anwser 的函数pairwise 轻松完成此操作

        def pairwise(iterable):
            a = iter(iterable)
            return izip(a, a)
        
        for f1, f2 in pairwise(os.listdir(os.curdir)):
            print f1 + '\t' + f2
        

        【讨论】:

        • 问题是如果元素的数量是奇数,它会错过最后一个元素。
        【解决方案4】:

        试试这个,

        for i,k in zip(os.listdir(os.curdir)[0::2], os.listdir(os.curdir)[1::2]): print i,k
        

        【讨论】:

          猜你喜欢
          • 2014-08-11
          • 1970-01-01
          • 1970-01-01
          • 2013-05-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-23
          • 1970-01-01
          相关资源
          最近更新 更多