Python打印列表并排

时间:2016-07-15 21:41:03

标签: python dictionary multiple-columns

大家。我是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

3 个答案:

答案 0 :(得分:2)

依赖于tabulate module

package xyz.adamstephenson.android.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.content.Intent;

import static
xyz.adamstephenson.android.myapplication.R.layout.activity_main;


public class MyActivity extends Activity {
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(activity_main);

        final Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d("button", "This is my message");
            }
        });
    }
}

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

答案 2 :(得分:0)

我确定您可以手动构建自己的库,但Python似乎有一个内置于字符串类型的格式方法,可以很好地满足您的需要。

以前帖子的link可以帮到你!试一试!