Reputation: 1499
everyone. I am new to Python and in dire need of some help. I am trying to count the unique values in a few lists and then print the output side by side as columns. I can count them fine using collections. However, I don't know how to print them side by side. Is there any pythonic way to concatenate or display them as columns side by side?
I tried the below but to no avail. ANY help is well appreciated.
print(str(parsed_list(a)) + str(parsed_list(b)) + str(parsed_list(b)))
NoneNoneNone
My Sample Testable Code (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)
Current:
Column1 Column2 Column3
---------------------------------------------
Black Cat 1
Black Dog 1
Black Mouse 1
Bird 2
Parrot 1
Eagle 3
Hawk 1
Desired Output:
Column1 Column2 Column3
----------------------------------------
Black Cat 1 Bird 2 Eagle 3
Black Dog 1 Parrot 1 Hawk 1
Black Mouse 1
Upvotes: 0
Views: 2480
Reputation: 60143
Taking a dependency on the tabulate module:
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
Upvotes: 2
Reputation: 113834
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))
This produces:
Black Cat 1 Bird 2 Eagle 3
Black Mouse 1 Parrot 1 Hawk 1
Black Dog 1
Upvotes: 1
Reputation: 2911
Im sure you can manually build your own library, but Python seems to have a format method built into the string type that could work well for your purpose.
This link of a previous post can help you out! Give it a shot!
Upvotes: 0