I need to print a list in matrix form. I need to remove the brackets and commas from the list. I don't know how to do that so please help me to find a solution.
This is my code:
import re
import itertools
import textwrap
a,b=map(int,input().split())
c=[]
pv=[]
av=[]
for i in range(a):
row=input().split()
c.append(row)
c=list(itertools.chain(*c))
for i in range(len(c)):
ab=c[i]
res="".join(a *int(b) for a, b in zip(ab[0::2],ab[1::2]))
pv.append(res)
pv1=[]
for i in range(b):
cd=pv[i::b]
pv1.append(cd)
pv1=list(itertools.chain(*pv1))
pv2=[]
for i in range(len(pv1)):
abd=pv1[i]
r=textwrap.wrap(abd,3)
pv2.append(r)
pv2=list(itertools.chain(*pv2))
pv2=[list(pv) for pv in pv2]
pavi=int(len(pv2)/b)
pv2=[pv2[i:i pavi] for i in range(0,int(len(pv2)),pavi)]
for row in zip(*pv2):
print(*(row))
My output:
2 3
a3b3c3 b1c1a7 x4y1z4
p9 a8c1 z2y2x5
['a', 'a', 'a'] ['b', 'c', 'a'] ['x', 'x', 'x']
['b', 'b', 'b'] ['a', 'a', 'a'] ['x', 'y', 'z']
['c', 'c', 'c'] ['a', 'a', 'a'] ['z', 'z', 'z']
['p', 'p', 'p'] ['a', 'a', 'a'] ['z', 'z', 'y']
['p', 'p', 'p'] ['a', 'a', 'a'] ['y', 'x', 'x']
['p', 'p', 'p'] ['a', 'a', 'c'] ['x', 'x', 'x']
Expected Output:
2 3
a3b3c3 b1c1a7 x4y1z4
p9 a8c1 z2y2x5
a a a b c a x x x
b b b a a a x y z
c c c a a a z z z
p p p a a a z z y
p p p a a a y x x
p p p a a c x x x
So this is the output I needed. I zipped the list into equal halves but I don't know how to remove the spaces and brackets. So please help me out, guys.
CodePudding user response:
Instead of print(*(row)) at the end, you could just do
print(re.sub(r"[^\w ]", "", str(row)))
This will remove every character that is not a word character or space.
CodePudding user response:
Since you've already imported itertools, you could use chain for printing each line:
for row in zip(*pv2):
print(*itertools.chain(*row))
Alternatively, you could expand and break down the patterns in progressive list comprehensions:
width = 3
strings = [ ['a3b3c3','b1c1a7','x4y1z4'],
['p9','a8c1','z2y2x5'] ]
# expand run-lengths into the repeated character sequences
strings = [ ["".join(c*int(n) for c,n in zip(*[iter(rle)]*2)) for rle in row]
for row in strings ]
# break down each string based on specified wrapping width
strings = [ [ [s[i:i width] for i in range(0,len(s),width)] for s in row]
for row in strings ]
# combine the broken down chunks for each column
strings = [ s for row in strings for s in map("".join,zip(*row)) ]
# print the result
for line in strings: print(*line)
a a a b c a x x x
b b b a a a x y z
c c c a a a z z z
p p p a a a z z y
p p p a a a y x x
p p p a a c x x x
Note that you may need to use zip_longest for the chunk combining part if the input doesn't always produce equal size blocks of characters
