2016-07-15 12 views
0

皆さん。私はPythonの初心者であり、助けが必要です。私はいくつかのリストで一意の値を数え、次に出力を列として印刷しようとしています。私はコレクションを使って細かく数えることができます。しかし、私はそれらを並べて印刷する方法を知らない。列を並べて並べて表示する方法はありますか?Python印刷リストを並べて表示

私は以下を試したが、役に立たなかった。どんな助けでも大歓迎です。

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 
+0

は、あなたがそのような表形式のデータを扱うためにパンダを使用して見ていますか? –

+0

@ cricket_007残念ながら、このスクリプトは私がPandasをインストールできない(許可されていない)システム上で実行されています。これを行うネイティブな方法はありませんか?頻繁に必要とされるようなものです。 – MBasith

答えて

0

イム必ず手動で独自のライブラリを構築することができますしかし、Pythonの形式はmethoのようですあなたの目的のためにうまくいくかもしれない文字列型に組み込まれています。

この投稿はlinkがお手伝いします。試してみます! tabulate moduleへの依存を取る

2

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 
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