I have a list of 2D elements
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
and I want my output to be:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
I tried this loop:
for i in range(3):
for k in range(i,len(m),3):
print(*m[i][k:k+3],sep='\t')
but it prints
1 2 3
4 5
6 7 8
9 10
11 12 13
14 15
16 17 18
and gives me an error
I'm not sure if it is possible since it is going on the next element. Can anyone help me on this?
An approach like this would work:
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
curr = 0
for i in m:
for j in i:
curr += 1
if(curr % 3 == 0):
print(j)
else:
print(j, end = ' ')
Output:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
You can create a variable, curr, to act as a counter variable. Then, iterate through every element of m, and increment curr with each iteration. For every third element, given by curr % 3 == 0%, we print an element WITH a newline. For every not-third element, we print the element without a newline.
I hope this helped! Please let me know if you have any further questions or clarifications :)
import itertools
x = list(itertools.chain(*m))
print([x[i:i+3] for i in range(0,len(x),3)])
Of course, the above will print the whole thing as a list of lists, but you can go from there to printing each of the individual sublists.
I would try something like
count = 0
for arr in matrix:
for num in arr:
print(num, end=' ')
count += 1
if count == 3:
print()
count = 0
one-line version:
print("".join([str(e)+" " if e%3!=0 else str(e)+"\n" for row in m for e in row]))
P.S. m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]] as that of OP.
easy-to-read version:
m does not need to be identical to that of OP. Could be any 2d matrix.
flat = [e for row in m for e in row]
for i in range(len(flat)):
if i%3 != 2 : print(flat[i], end = " ")
else : print(flat[i], end = "\n")
if len(flat)%3 != 0: print("")
You can use this snippet
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
flag=0
for i in range(len(m)):
for j in range(len(m[i])):
if(flag==3):
print()
flag=0
print(m[i][j],end=" ")
flag+=1
It has multiple ways to do that but easiest way is one line approaching using list comprrehension.
flat = [element for sublist in m for element in sublist]
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
flat = [element for sublist in m for element in sublist]
print("Original list", m)
print("Flattened list", flat)
itertools.chain combines all the sublists, and more_itertools.chunked breaks that up into equal-sized segments.
from itertools import chain
from more_itertools import chunked
m = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
for triplet in chunked(chain(*m), 3):
print(*triplet)
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
(The asterisks are for unpacking; in this case print(*triplet) is effectively the same as print(triplet[0], triplet[1], triplet[2]), and print automatically inserts a space between multiple arguments by default.)
P.S. Nine times out of ten, if you're mucking about with indexes in a Python loop, you don't need to.
Related
I'm trying get the first 3 elements of a list.
1 a = "101.10.10.10"
2
3 b = "102.12.12.12"
4
5
6 asplit = a.split(".")
7 print("a - ")
8 print(asplit)
9
10 bsplit = b.split(".")
11 print("b - ")
12 print(bsplit)
13
14 print()
15 print()
16
17 print("---")
18 print (a[0], a[3])
when i'm using this code it returns
1 and .
i want to print
101 10 10
or
102 12 12
We can combine list comprehension, split() function, join() function and slicing to do that. At first, we split the string from dots. Then we create a list comprehension which will eliminate empty string. Then we join it, as a final step we use the [0:3] slice.
b = "102.12.12.12"
print(' '.join([x for x in b.split('.') if x != ''][0:3]))
In [1]: a = "101.10.10.10"
In [2]: " ".join(a.split(".")[:3])
Out[2]: '101 10 10'
In [3]: b = "102.12.12.12"
In [4]: " ".join(b.split(".")[:3])
Out[4]: '102 12 12'
In this Program I need to rotate the matrix by one element in clockwise direction.I had done with the code but I have a problem with removing the newlione in the the last row in the given Matrix. In this Program the user has to give the input. The code is
def rotate(m):
if not len(m):
return
top=0
bottom=len(m)-1
left=0
right=len(m[0])-1
while(left<right and top < bottom):
prev=m[top+1][left]
for i in range(left,right+1):
curr=m[top][i]
m[top][i]=prev
prev=curr
top+=1
for i in range(top,bottom+1):
curr=m[i][right]
m[i][right]=prev
prev=curr
right-=1
for i in range(right,left-1,-1):
curr=m[bottom][i]
m[bottom][i]=prev
prev=curr
bottom-=1
for i in range(bottom,top-1,-1):
curr=m[i][left]
m[i][left]=prev
prev=curr
left+=1
return m
def printMatrix(m):
for row in m:
print(' '.join(str(n) for n in row))
n = int(input())
m = []
for i in range(1,n+1):
l = list(map(int, input ().split ()))
m.append(l)
marix=rotate(m)
printMatrix(m)
The Test Case is given Below
Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Expected Output:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12
Actual Output Which i get:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12\n
This is just an issue with your printMatrix() function, print() by defaults adds a newline. You could replace it with below to eliminate the last newline (though I'm not sure why this is so critical):
def printMatrix(m):
print('\n'.join(' '.join(str(n) for n in row) for row in m), end='')
I'm not sure how to do this. I know how to print a square shape by prompting for row and col, but don't quite understand how to only prompt for height and print an array of even numbers.
col = eval(input("Enter the number of columns: "))
row = eval(input("Enter the number of rows: "))
for j in range(row):
for i in range(col):
print("*", end=" ")
print()
this is how I would set up printing a square of asterisks, but how would I do this while only prompting for height and printing out even numbers? For example, if my height is "3", it should print out an array that looks like this:
0 2 4
6 8 10
12 14 16
Using next() on an iterator of the numbers:
h = 3
ns = iter(range(0,h**2*2,2))
for r in range(h):
for c in range(h):
print(next(ns), end='\t')
print()
which gives:
0 2 4
6 8 10
12 14 16
Using slicing and str.join:
h = 4
ns = list(range(0,h**2*2,2))
for r in range(0,len(ns),h):
print(" ".join(str(c) + "\t" for c in ns[r:r+h]))
which gives:
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30
Here is an approach by making a nested list and printing it out using a formatting function. Can replace the list comprehension with a generator comprehension for large lists.
def print_even_matrix(h):
l = [[2*(i + j) for j in range(h)] for i in range(0, h**2, h)]
listtab = lambda x: '\t'.join(map(str, x))
print '\n'.join(map(listtab, l))
>>> print_even_matrix(3)
0 2 4
6 8 10
12 14 16
>>> print_even_matrix(4)
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30
Please close if this is a duplicate, but this answer does not answer my question as I would like to print a list, not elements from a list.
For example, the below does not work:
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(%3s % mylist)
Desired output:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Basically, if all items in the list are n digits or less, equal spacing would give each item n+1 spots in the printout. Like setw in c++. Assume n is known.
If I have missed a similar SO question, feel free to vote to close.
You can exploit formatting as in the example below. If you really need the square braces then you will have to fiddle a bit
lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
frmt = "{:>3}"*len(lst)
print(frmt.format(*lst))
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
items=range(10)
''.join(f'{x:3}' for x in items)
' 0 1 2 3 4 5 6 7 8 9'
If none of the other answers work, try this code:
output = ''
space = ''
output += str(list[0])
for spacecount in range(spacing):
space += spacecharacter
for listnum in range(1, len(list)):
output += space
output += str(list[listnum])
print(output)
I think this is the best yet, as it allows you to manipulate list as you wish. even numerically.
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(*map(lambda x: str(x)+" ",a))
Given a set or a list (assume its ordered)
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
I want to find out how many numbers appear in a range.
say my range is 10. Then given the list above, I have two sets of 10.
I want the function to return [10,10]
if my range was 15. Then I should get [15,5]
The range will change. Here is what I came up with
myRange = 10
start = 1
current = start
next = current + myRange
count = 0
setTotal = []
for i in myset:
if i >= current and i < next :
count = count + 1
print str(i)+" in "+str(len(setTotal)+1)
else:
current = current + myRange
next = myRange + current
if next >= myset[-1]:
next = myset[-1]
setTotal.append(count)
count = 0
print setTotal
Output
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 8]
notice 11 and 20 where skipped. I also played around with the condition and got wired results.
EDIT: Range defines a range that every value in the range should be counted into one chuck.
think of a range as from current value to currentvalue+range as one chunk.
EDIT:
Wanted output:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 10]
With the right key function, thegroupbymethod in the itertoolsmodule makes doing this fairly simple:
from itertools import groupby
def ranger(values, range_size):
def keyfunc(n):
key = n/(range_size+1) + 1
print '{} in {}'.format(n, key)
return key
return [len(list(g)) for k, g in groupby(values, key=keyfunc)]
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print ranger(myset, 10)
print ranger(myset, 15)
You want to use simple division and the remainder; the divmod() function gives you both:
def chunks(lst, size):
count, remainder = divmod(len(lst), size)
return [size] * count + ([remainder] if remainder else [])
To create your desired output, then use the output of chunks():
lst = range(1, 21)
size = 10
start = 0
for count, chunk in enumerate(chunks(lst, size), 1):
for i in lst[start:start + chunk]:
print '{} in {}'.format(i, count)
start += chunk
count is the number of the current chunk (starting at 1; python uses 0-based indexing normally).
This prints:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
20 in 2
If you don't care about what numbers are in a given chunk, you can calculate the size easily:
def chunk_sizes(lst, size):
complete = len(lst) // size # Number of `size`-sized chunks
partial = len(lst) % size # Last chunk
if partial: # Sometimes the last chunk is empty
return [size] * complete + [partial]
else:
return [size] * complete