I had 109 CT scans of my head, and I was going to try to reconstruct it in three dimensions. One of the basic tasks is to read the image data and organize it into a three-dimensional data structure (actually four-dimensional, since each pixel has four RGBA channels).
This data structure, of course, is numpy’s NDARray object, and I’m used to reading image files using PIL. Therefore, two modules need to be imported:
import numpy as npfrom PIL import Image
Copy the code
I then read 109 images into a 109x256x256x4 numpy array in one line of code in 172 milliseconds:
data = np.stack([np.array(Image.open('head%d.png'%i)) for i in range(109)], axis=0)
Copy the code
In general, the above line of code would look like this:
data = list()for i in range(109): img = Image.open('head%d.png'%i) img = np.array(img) data.append(img)data = np.stack(data, axis=0)
Copy the code
I wrote this code in a single line, but it was as beautiful as poetry, as popular as natural language!
At that moment, my imagination was full and I wondered what python gurus could do with a single line of code. Of course, the qualification is that you can’t reference custom modules, you can use built-in modules or generic third-party modules. A quick Internet search shows that the problem seems to be python specific, and it’s hard for other languages to do anything with one line of code. Zhihu has an article titled “What Crazy Thing can a Single Line of Python Do?” “, its mirror post is only Java and JS, click to find, and Python is completely different concept.
Sorted out the content of this article on Zhihu, quite feel interesting, share with you.
1. One line of code prints the multiplication table
Print (' \ n '. Join (['. Join ([" % 2 s x % 2 s = % 2 s "% (j, I, I * j) for j in range (1, I + 1)]) for I in range (1, 10))))Copy the code
2. One line of code prints the maze
print(''.join(__import__('random').choice('\u2571\u2572') for i in range(50*24)))
Copy the code
3. A line of code to express love
Print (' \ n '. Join ([(' Love ' ' '. Join ([[(x-y) % len (' Love ')] the if ((0.05) x * * * 2 + 0.1) (y * * * 2-1) 3 - (0.05) x * * * * * 2 * * * 3 (y * 0.1) < = 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))Copy the code
4. One line of code prints the turtle
print('\n'.join([''.join(['*' if abs((lambda a:lambda z,c,n:a(a,z,c,n))(lambda s,z,c,n:z if n==0 else S (s, z * z + c, c, n - 1)) (0,0.02 0.05 j * * x + y, 40)) < 2 else 'for x in the range (80, 20 -)]) for y in range (20, 20 -)))Copy the code
What exciting one-line feature have you implemented in Python?