+ 1
How to print list of numbers in blocks?
Hello there, Can someone advise or hint on how I can use a simple loop to print a randomized list of 16 numbers in a 4 x 4 matrix? My code Is as attachéd. Thanks and Regards Ben https://code.sololearn.com/c4L2lirX6J7K/?ref=app
15 Antworten
+ 5
Check this code you can use numpy for this.
https://code.sololearn.com/cl3q5hIjjt4B/?ref=app
+ 4
[print(*myList[x:x+4]) for x in range(0,len(myList),4)]
+ 3
myList = list(range(1,17))
matrix = []
for i in range(0,len(myList),4):
matrix.append(myList[i:i+4])
for i in matrix:
print(" ".join(str(j) for j in i))
"What is a docstring?"
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2288/
+ 3
Ben why do you want this exactly same output,but in your code list is rearranging differently at every execution due to random module.
+ 2
hi @Cbr, what is a doc string?
+ 2
@diego, thabks for the help. but im looking for a result like this:
5 7 15 1
8 16 6 2
4 9 10 11
12 14 13 3
+ 2
Maninder $ingh i dont need this exact same output, it is just an example of what I need. i have just tried your code, the output seems to be what i need! :) thank you!
+ 2
Diego your code doesn’t seem to work?
+ 2
Diego i see, ive tried and it works! ill need some time to understand the .append method, it seems you have create lists within a list! its really a cool solution!
thank you so much for the help!
+ 2
Diego may i know what is the meaning of this part you wrote:
for i in matrix:
print(“ “.join(str(j) for j in i))
in particular the part “for j in i”, what does this mean?
+ 1
It's called a list comprehension. Here's a great tutorial about it:
https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
If you have any more doubts you can always message me (if you're on Android).
+ 1
Louis thank you for such an elegant solution!
why is it possible to add a for loop after the print function?
+ 1
hi guys, played around abit with @louis code, and this is the format i understand and works:
for x in range(0,len(myList),4):
print(*myList[x:x+4])
one question: why does the “*” magically removes the “list brackets [ ]”?
+ 1
hi guys, played around abit with @louis code, and this is the format i understand and works:
for x in range(0,len(myList),4):
print(*myList[x:x+4])
one question: why does the “*” magically removes the “list brackets [ ]”?
0
Ben It's the power of list comprehensions.
The "*" is unpacking the elements of the list. If you use it inside the print() function you won't be passing a list as argument, but the elements inside it.
print(*[4, 2]) # 4 2
print(4, 2) # 4 2
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2485/