簡體   English   中英

Python打印列表並排

[英]Python printing lists side by side

大家。 我是Python的新手,迫切需要一些幫助。 我試圖在幾個列表中計算唯一值,然后將輸出並排打印為列。 我可以用收藏算一下。 但是,我不知道如何並排打印它們。 是否有任何pythonic方式將它們並排顯示為列?

我嘗試了以下但無濟於事。 任何幫助都非常感謝。

print(str(parsed_list(a)) + str(parsed_list(b)) + str(parsed_list(b)))
NoneNoneNone

我的示例可測試代碼(Python3):

import collections, operator

a = ['Black Cat', 'Black Dog', 'Black Mouse']
b = ['Bird', 'Bird', 'Parrot']
c = ['Eagle', 'Eagle', 'Eagle', 'Hawk']


def parsed_list(list):
    y = collections.Counter(list)
    for k, v in sorted(y.items(), key=operator.itemgetter(1), reverse=True):
        z = (str(k).ljust(12, ' ') + (str(v)))
        print(z)

print('Column1          Column2             Column3')
print('-' * 45)
parsed_list(a)
parsed_list(b)
parsed_list(c)

當前:

Column1          Column2             Column3
---------------------------------------------
Black Cat   1
Black Dog   1
Black Mouse 1
Bird        2
Parrot      1
Eagle       3
Hawk        1

所需輸出:

Column1          Column2      Column3
----------------------------------------
Black Cat   1    Bird     2   Eagle  3
Black Dog   1    Parrot   1   Hawk   1
Black Mouse 1

依賴於制表模塊

import collections
from itertools import zip_longest
import operator

from tabulate import tabulate

def parsed_list(lst):
    width = max(len(item) for item in lst)
    return ['{key} {value}'.format(key=key.ljust(width), value=value)
            for key, value in sorted(
                collections.Counter(lst).items(),
                key=operator.itemgetter(1), reverse=True)]

a = parsed_list(['Black Cat', 'Black Dog', 'Black Mouse'])
b = parsed_list(['Bird', 'Bird', 'Parrot'])
c = parsed_list(['Eagle', 'Eagle', 'Eagle', 'Hawk'])

print(tabulate(zip_longest(a, b, c), headers=["Column 1", "Column 2", "Column 3"]))

# Output:
# Column 1       Column 2       Column 3
# -------------  -------------  -------------
# Black Mouse 1  Bird        2  Eagle       3
# Black Dog   1  Parrot      1  Hawk        1
# Black Cat   1
from collections import Counter
from itertools import zip_longest
a = ['Black Cat', 'Black Dog', 'Black Mouse']
b = ['Bird', 'Bird', 'Parrot']
c = ['Eagle', 'Eagle', 'Eagle', 'Hawk']

def parse(lst):
    c = Counter(lst)
    r = []
    for s, cnt in c.most_common():
        r += ['%12s%3i' % (s, cnt)]
    return r 

for cols in zip_longest(parse(a), parse(b), parse(c), fillvalue=15*' '):
    print(' '.join(cols))

這將產生:

   Black Cat  1         Bird  2        Eagle  3
 Black Mouse  1       Parrot  1         Hawk  1
   Black Dog  1                                

我確定您可以手動構建自己的庫,但是Python似乎在字符串類型中內置了一種格式化方法,可以很好地滿足您的目的。

上一篇文章的此鏈接可以幫助您! 試一試!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM