Make lists with out commas in python - python

I want to make a list of list without comma.
data=[[2,124,123],[3,4,5]]
for i in data:
print(x[0],x[1],x[2])
gives
2 124 123
3 4 5
How do I write the code so that it gives me:
[ 2 124 123 ]
[ 3 4 5 ]
for any kind of input with out using built in functions. The number of paddings for all elements is equal to the length of the largest element in the the list.
Thank you in advance.

Just unpack the arguments to print, eg:
data=[[2,124,123],[3,4,5], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
for i in data:
print(*i)
Gives:
2 124 123
3 4 5
1 2 3 4 5 6 7 8 9 10
If you only wanted the first n many then slice it, then unpack it, eg:
for i in data:
print(*i[:3])
Not sure what you mean by "without builtin" functions, as that just seems silly. Find the max length to pad, then apply it as such:
from itertools import chain
data=[[2,124,123],[3,4,5]]
max_padding = max(len(str(el)) for el in chain.from_iterable(data))
for i in data:
print(' '.join([str(el).rjust(max_padding) for el in i]))
Gives:
2 124 123
3 4 5
If you actually want brackets around it, then it's easy enough to add them in...

Is the below doing what you want?
for i in data:
print("[" + ' '.join(str(x) for x in i) + "]")

Related

String-formatting two zipped NumPy arrays in Python 3

I would like to use pythons format function to print subsequent numbers of a numpy array.
I have got two numpy arrays, let's say:
x=[1 2 3 4]
y=[5 6 7 8]
Now I would like to print this:
1 5 2 6 3 7 4 8
I can almost achieve this by:
print('{} {} {} {}'.format(*zip(x,y)))
but it yields:
(1,5) (2,6) (3,7) (4,8)
Of course I could use
"{} {} {} {}".format(x[0], y[0], x[1], y[1])
and so on but this requires to know the length of the array.
Note:
This line of code does what I want
print(*["%f %f"%(a,b) for a,b in zip(x,y)])
but this does use the old formatting style and I would like to know if it's possible with the new one, too. It also looks a little bit funky, I think :-D
Do the following:
x=[1, 2, 3, 4]
y=[5, 6, 7, 8]
result = ' '.join([str(i) for e in zip(x, y) for i in e])
print(result)
Output
1 5 2 6 3 7 4 8
You can use itertools.chain to interleave the elements from both lists:
list(chain.from_iterable(zip(x, y)))
[1, 5, 2, 6, 3, 7, 4, 8]
And if you want to print all elements joined as you specify you can do:
print(*chain.from_iterable(zip(x, y)))
1 5 2 6 3 7 4 8
what about some numpy
np.array(list(zip(a,b))).flatten()
output
array([1, 5, 2, 6, 3, 7, 4, 8])
You can use zip() to iterate through two iterables at the same time.
l1 = [0, 2, 4, 6, 8]
l2 = [1, 3, 5, 7, 9]
for i, j in zip(l1, l2):
print(i)
print(j)
Output:
0
1
2
3
4
5
6
7
8
9
Since you use numpy, what about
>>> ' '.join(np.vstack((x, y)).T.flatten().astype(str))
'1 5 2 6 3 7 4 8'
It's also possible with itertools.starmap:
>>> print(*starmap("{} {}".format, zip(x, y)))
1 5 2 6 3 7 4 8
Normally, the method given by #yatu with itertools.chain is the way to go, especially if you want all elements to be separated by spaces. But starmap could come handy when you'd want to have some special formatting between the pairs, for example:
>>> print(*starmap("{}:{}".format, zip(x, y)))
1:5 2:6 3:7 4:8
Throwing another into the mix
("{} "*len(x)*2).format(*np.ravel(list(zip(x,y))))
'1 5 2 6 3 7 4 8 '

Keeping Python from spacing after breaking a line when printing a List

(yes, I've searched all around for a solution, and, if did I see it, I wasn't able to relate to my issue. I'm new to Python, sorry!)
I've got a work to do, and it says to me:
"User will input X and Y. Show a sequence from 1 to Y, with only X elements each line."
e.g
2 4 as entrance
1 2
3 4
e.g 2 6
1 2
3 4
5 6
Okay... So, I thought on doing this:
line, final = input().split()
line = int(line)
final = int(final)
List = []
i = 0
total = (final // line)
spot = 0
correction = 0
k = 1
if i != final:
List = list(range(1, final + 1, 1))
i += 1
while k != total:
spot = line * k + correction
correction += 1
k += 1
list.insert(List, spot, '\n')
print(*List)
Ok. So I managed to build my List from 1 to the "final" var.
Also managed to find on which spots (therefore, var "spot") my new line would be created. (Had to use a correction var and some math to reach it, but it's 10/10)
So far, so good.
The only problem is this work is supposed to be delivered on URI Online Judge, and it DEMANDS that my result shows like this:
2 10 as entrance
1 2
3 4
5 6
7 8
9 10
And, using the code I just posted, I get this as a result:
1 2
3 4
5 6
7 8
9 10
Thus, it says my code is wrong. I've tried everything to remove those spaces (I think). Using sys won't work since it only prints one argument. Tried using join (but I could have done it wrong, as I'm new anyway)
Well, I've tried pretty much anything. Hope anyone can help me.
Thanks in advance :)
You have built a list that includes each necessary character, including the linefeed. Therefore, you have a list like this:
[1, 2, '\n', 3, 4, '\n'...]
When you unpack arguments to print(), it puts a separator between each argument, defaulting to a space. So, it prints 1, then a space, then 2, then a space, then a linefeed, then a space... And that is why you have a space at the beginning of each line.
Instead of inserting linefeeds into a list, chunk that list with iter and next:
>>> def chunks(x, y):
... i = iter(range(1, y+1))
... for row in range(y//x):
... print(*(next(i) for _ in range(x)))
... t = tuple(i)
... if t:
... print(*t)
...
>>> chunks(2, 6)
1 2
3 4
5 6
>>> chunks(2, 7)
1 2
3 4
5 6
7
The problem with the approach you're using is a result of a space being printed after each "\n" character in the series. While the idea was quite clever, unfortunately, I think this means you will have to take a different approach from inserting the newline character into the list.
Try this approach: (EDITED)
x, y = input().split()
x, y = int(x), int(y)
for i in range(1, y+1):
if i % x == 0 or i == y:
print(i)
else:
print(i, end=" ")
Output for 3 11
1 2 3
4 5 6
7 8 9
10 11
Output for 2 10
1 2
3 4
5 6
7 8
9 10
Use itertools to take from an iterable in chunks:
>>> import itertools
>>> def print_stuff(x,y):
... it = iter(range(1, y + 1))
... chunk = list(itertools.islice(it,X))
... while chunk:
... print(*chunk)
... chunk = list(itertools.islice(it,X))
...
>>> print_stuff(2,4)
1 2
3 4
>>>
And here:
>>> print_stuff(2,10)
1 2
3 4
5 6
7 8
9 10
>>>
I split user input into two string then convert them into int and comapre if y greater than x by 2 because this is minimum for drawing your sequence
Then i make a list from 1 to y
And iterate over it 2 element for each iteration printing them
x,y=input().split()
if int(y)>int(x)+2:
s=range(1,int(y)+1)
for i in range(0,len(s),2):
print(' '.join(str(d) for d in s[i:i+2]))
result:
1 2
3 4
5 6
7 8
9 10

Rearranging numbers from list in python3

Lets say I have an list of numbers
a = [ 1,2,3,4,5,6,7,8,9,10]
and I want to print the output as
1
2 3
4 5 6
7 8 9 10
How can I do it in python3.
My attempt:
a = [1,2,3,4,5,6,7,8,9,10]
for i in a:
print(a[i]," ")
i=i+1
I'm getting IndexError: list index out of range and also I don't know to print 1 element in 1'st row , 2nd and 3rd in second row and so on.
One way to do this in Python 3 is to use islice on an iterator :
from itertools import islice
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
it = iter(a)
print('\n'.join([' '.join([str(u)for u in islice(it, i)])for i in range(1,5)]))
output
1
2 3
4 5 6
7 8 9 10

python printing list items incremented on lines

I am trying to take a user input and print out a list of numbers in a box format onto different lines in python.
right now i have:
horizontalsize = int (input ('please enter horizontal size '))
verticalsize = int (input ('please enter vertical size '))
numbers = horizontalsize * verticalsize
mylist = []
mylist.append(range(1,numbers))
for i in range(1,numbers,horizontalsize):
print (i)
The user will input a height and width and if the height input is 5 and the width input is 3 it should print:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
right now im currently getting:
1
4
7
10
13
How can i get the rest of the numbers to fill in?
Any help is greatly appreciated!
This should work:
for i in range(1, numbers, horizontalsize):
lst = range(i, i+horizontalsize)
print lst # format is [1,2,3]
print ' '.join(map(str,lst)) # format is "1 2 3"
You can also declare a 2D list by list comprehension, example:
>>> horizontalsize = 3
>>> numbers = 15
>>> ll = [[x for x in range(y,y+horizontalsize)]
for y in range(1,numbers,horizontalsize)]
>>> ll
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
>>> for line in ll:
... print ' '.join(map(str,line))
...
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
The range() you are using will start at 1, go up to numbers, and increase by horizontalsize each time. You are pulling your values for i directly from that range, so those will be the only values you get. One simple solution is to add a second, nested loop to generate the missing values (between i and i+horizontalsize).
for i in range(1,numbers,horizontalsize):
for j in range(i, i+horizontalsize):
print (j, end=" ")
print() #for the newline after every row
Your loop steps skips all the numbers between 1 and 1+horizontalsize, and you just print that number out (without worrying about putting things on the newline). You either need to insert a nested for loop, or modify your range to go over every number, and then put the newline only after specific ones.
That second solution, which uses modulo operator:
for i in range(1,(numbers+1)):
print(i,end=" ")
if i % horizontalsize == 0:
print()
Which gives me:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15

formatting output with for loop or different method in python

I did a program to calculate the inventory in python;however, i have problem formatting the layout output. What I have done so far is:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
for j in range(col):
print "%6d" %(a[i][j]),
print "%s%6d\n" %(d[i],(b[i])),
print "\n" ,
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
so the output comes the 7 x 4 matrix and the total to the right hand side and by column total. However I want to put some names on the left hand side to represent the specific name like size small etc so i used a dictionary but what i am getting is on the right hand side just before the row total. I can't figure out how can i put it on the left hand side in the same row as the numbers. I want to put two columns apart from the number (matrix) which one would be a size in the first far left column in the middle and then in second column names as u can see specified used in dictionary and then the numbers would come in the same row.
Thanks a lot for any help or suggestions. I did a program to calculate the inventory in python;however, i have problem formatting the layout output. What I have done so far is:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
for j in range(col):
print "%6d" %(a[i][j]),
print "%s%6d\n" %(d[i],(b[i])),
print "\n" ,
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
so the output comes the 7 x 4 matrix and the total to the right hand side and by column total. However I want to put some names on the left hand side to represent the specific name like size small etc so i used a dictionary but what i am getting is on the right hand side just before the row total. I can't figure out how can i put it on the left hand side in the same row as the numbers. I want to put two columns apart from the number (matrix) which one would be a size in the first far left column in the middle and then in second column names as u can see specified used in dictionary and then the numbers would come in the same row.
Thanks a lot for any help or suggestions.
I want it to look like this
small 1 1 1 1 1 1 1 7
medium 1 1 1 1 1 1 1 7
size large 1 1 1 1 1 1 1 7
xlarge 1 1 1 1 1 1 1 7
4 4 4 4 4 4 4 28
and i get
1 1 1 1 1 1 1 small 7
1 1 1 1 1 1 1 medium 7
1 1 1 1 1 1 1 large 7
1 1 1 1 1 1 1 xlarge 7
4 4 4 4 4 4 4 28
sorry for not being specific enough previously.
Just print it before the row:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
print d[i].ljust(6),
for j in range(col):
print "%6d" %(a[i][j]),
print "%6d\n" %(b[i]),
print "\n" ,
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
This assumes you want the first column left justified. Right justification (rjust()) and centering (center()) are also available.
Also, since you're just using contiguous numeric indices, you can just use a list instead of a dictionary.
As a side note, more descriptive variables are never a bad thing. Also, according to this, % formatting is obsolete, and the format() method should be used in new programs.
You just have to move the "%s" and the appropriate variable to the correct position:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
print "%8s" % d[i],
for j in range(col):
print "%6d" %(a[i][j]),
print "%6d\n" % ((b[i])),
print "\n" ,
print "%8s" % " ",
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
When calling this with (note that this are just test-numbers, you will replace them with the real ones):
summary([[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7]], [12, 13, 14, 15],
[22, 23, 24, 25, 26, 27, 28], 4, 7, 7777)
you get something like:
Small 1 2 3 4 5 6 7 12
Medium 1 2 3 4 5 6 7 13
Large 1 2 3 4 5 6 7 14
Xlarge 1 2 3 4 5 6 7 15
22 23 24 25 26 27 28 7777
If you want the names left adjusted, you have to add a '-' before the format description like:
print "%-8s" % d[i],

Categories