A single line of Python code can achieve insanity


I have 109 CT scans of the head on hand, and I’m going to try three-dimensional reconstruction of the head with these images. One of the basic tasks is to read out the image data and organize it into a three-dimensional data structure (actually four-dimensional, because each pixel has four RGBA channels).

This data structure, of course, is the ndarray object of numpy. I’m used to using PIL to read image files. Therefore, you need to import two modules:

import numpy as np
from PIL import Image

Next, I read 109 images into a numpy array of 109x256x256x4 in one line of code, taking 172 milliseconds

data = np.stack([np.array(Image.open('head%d.png'%i)) for i in range(109)], axis=0)

Usually, the above line of code should be written as follows:

data = list()
for i in range(109):
	img = Image.open('head%d.png'%i)
	img = np.array(img)
data = np.stack(data, axis=0)

I write these codes in a line, but there is no sense of obscurity, still as beautiful as poetry, as popular as natural language!

At that moment, my brain opened wide and I wanted to know what pythons could do with just one line of code? Of course, the qualification is that user-defined modules cannot be referenced. Built in modules or general third-party modules can be used. After searching the Internet, we found that this problem seems to be the exclusive problem of Python. It is very difficult for other languages to do something with a single line of code. There’s an article called “what can a line of Python do that’s insane?”? 》The image of the post is only Java and JS. Click in to find that it is not the same concept as python.

I have sorted out the content of this article on Zhihu. I find it interesting to share with you.

1. A line of code to print multiplication formula

print('\n'.join([' '.join(["%2s x%2s = %2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))

2. One line code printing maze

print(''.join(__import__('random').choice('\u2571\u2572') for i in range(50*24)))

3. A line of code to express love

print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0else' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))

4. One line of code printing 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*x+0.05j*y,40))<2 else ' ' for x in range(-80,20)]) for y in range(-20,20)]))

What exciting features have you implemented in a single line of code in Python? Welcome to leave a message for discussion.