【问题标题】:printing either a list or dictionary into columns将列表或字典打印到列中
【发布时间】:2015-11-05 21:47:31
【问题描述】:

我一直在研究如何将数据打印到列中。我无法找到一种优雅的方式来使用字典(键)或列表(将键从字典中取出到列表中)。

我已经研究过迭代每个键并打印它,但这不起作用,因为您不能使用映射。我尝试使用列表并使用string formatting 打印列表中的每个项目,但正如您想象的那样,我从每个列表项目中取回每个带有空格的字符,我似乎无法使用.join。我能够得到的最接近我想要的是来自Aaron Digullahere的答案。但是,这不会按字母顺序打印列表项。我不敢相信没有一种简单优雅的方法可以做到这一点?

上述答案的方法

l = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 
    'pdcurses-devel',     'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 
    'qgis1.1', 'php_mapscript']

if len(l) % 2 != 0:
    l.append(" ")

split = len(l)/2
l1 = l[0:split]
l2 = l[split:]
for key, value in zip(l1,l2):
    print "{0:<20s} {1}".format(key, value)

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    你可以使用排序,试试:

    l = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 
        'pdcurses-devel',     'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 
        'qgis1.1', 'php_mapscript']
    
    l.sort()# Alphabetizes l
    
    if len(l) % 2 != 0:
        l.append(" ")
    
    split = len(l)/2
    l1 = l[0:split]
    l2 = l[split:]
    for key, value in zip(l1,l2):
        print "{0:<20s} {1}".format(key, value)
    

    【讨论】:

    • arr 看来这确实有效,哈哈我以前尝试过,但我之前的尝试(设置 l1 和 l2 列表)已经离开,所以它似乎没有完成这项工作。所以正如你刚才提到的,我想我一定错过了一个把戏。谢谢马丁
    • 因为这是使用 zip 创建字典,因此可以安全地假设您不能拥有超过 2 列吗?毕竟你不能将超过 2 列压缩到一个字典中,可以吗?嗯,除非你可以嵌套它们?
    • zip 不是创建字典,它只是创建一系列元组,您碰巧将它们解包并调用keyvaluefor x, y, z in zip(l1, l2, l3) 甚至 for items in zip(l1, l2... l9) 之类的东西可以正常工作,但您还需要编辑字符串输出。
    【解决方案2】:

    这是一个更通用的版本,可让您指定列数:

    def print_in_columns(iterable, cols=2, col_width=20, key=None, reverse=False):
        # get items in output order
        items = sorted(iterable, key=key, reverse=reverse)
        # calculate number of output rows, and pad as needed
        rows = (len(items) + cols - 1) // cols
        pad  = rows * cols - len(items)
        items.extend("" for _ in range(pad))
        # prepare output template
        item_fmt = "{{:{}s}}".format(col_width)
        row_fmt  = " ".join(item_fmt for _ in range(cols))
        # print by row
        for r in range(rows):
            print(row_fmt.format(*(items[r::rows])))
    

    使用过类似

    files = [
        'exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 
        'pdcurses-devel',     'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 
        'qgis1.1', 'php_mapscript'
    ]
    
    print_in_columns(files, cols=4, col_width=16)
    

    生产

    exiv2-devel      iconv            netcdf           qgis-devel
    fcgi             mingw-libs       pdcurses-devel   qgis1.1
    gdal-grass       msvcrt           php_mapscript    tcltk-demos
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2017-07-02
      • 2013-02-16
      • 2015-05-29
      相关资源
      最近更新 更多