Reputation: 43
I'm trying to make a Pascal pyramid in python and I'm doing it with a list of lists, that way it's easier to insert the values I need it positions I need them, everything is working fine except when I print the list of lists it doesn't format correctly line by line the way I want it to
I've tried formatting with end=" ", and by using a * to unpack the list of lists however none of these seem to work
def unos(n,fila,columna,m):
mitad=columna//2
m[0][4]=1
for i in range(1,fila):
x=mitad+i
y=mitad-i
m[i][x]=1
m[i][y]=1
**print(*m)**#The error seems to be here(I could be wrong)
Python prints m this way: [0, 0, 0, 0, 1, 0, 0, 0, 0] [0, 0, 0, 1, 0, 1, 0, 0, 0] [0, 0, 1, 0, 0, 0, 1, 0, 0] [0, 1, 0, 0, 0, 0, 0, 1, 0] [1, 0, 0, 0, 0, 0, 0, 0, 1]
However what I need it printed out is this:
[0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 1, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 1, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 1]
Upvotes: 3
Views: 946
Reputation: 19885
To answer your question, we must inspect the unpacking operator (*
) and how it works with print
.
Recall that the unpacking operator takes a single iterable and turns it into multiple elements which are passed in series to a function.
Then, we know that print
takes multiple arguments in the form of args
, using a separator to separate them, if necessary. With this in mind, we can see that the four ways to print a b c
are equivalent:
print('a', 'b', 'c')
print(*['a', 'b', 'c'])
print(sep.join(['a', 'b', 'c']))
print('a' + sep + 'b' + sep + 'c')
...where sep
is, by default, (a single space).
Now, we note that m
is a nested list
. Therefore, by doing print(*m)
, what you are doing is effectively print(m[0], m[1]...m[-1])
, where m[0]
, m[1]...m-1
are individually lists
.
By referring to our analysis of print
above, we can see that that is the same as print(m[0] + ' ' + m[1] + ' ' + ... + ' ' + m[-1])
.
Clearly, there are no newlines in that, but there should be newlines where there are now spaces.
To get what we want, which is a newline after each element, therefore, we can just do print(*m, sep='\n')
.
Upvotes: 2
Reputation: 1158
you can use pprint:
import pprint
stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
stuff.insert(0, stuff)
pprint.pprint(stuff)
result :
[<Recursion on list with id=...>,
'spam',
'eggs',
'lumberjack',
'knights',
'ni']
you can see more examples here
Upvotes: 0
Reputation: 42678
You can use str.join
to show it all together in a string:
>>> print("\n".join("".join(str(e) for e in x) for x in l))
000010000
000101000
001000100
010000010
100000001
Where l
is your m
Upvotes: 1