One‑Line Python Tricks: Image Stacking and Creative One‑Liner Examples
This article shows how to load 109 head CT images into a NumPy ndarray with a single line of Python, then presents several whimsical one‑line Python scripts—including a multiplication table, maze printer, love‑message art, and turtle graphics—demonstrating the expressive power of concise code.
The author has 109 head CT slice images and demonstrates how to read them into a 4‑channel NumPy ndarray using Pillow, showing a concise one‑line solution that loads all images in 172 ms.
Typical multi‑line approach is also presented for comparison.
Typical multi‑line approach:
import numpy as np
from PIL import ImageOne‑line loading:
data = np.stack([np.array(Image.open('head%d.png'%i)) for i in range(109)], axis=0)Inspired by a Zhihu article about extreme one‑line Python tricks, the author shares several creative examples, each implemented in a single line of code.
1. One‑line multiplication table:
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 maze printer:
print(''.join(__import__('random').choice('\u2571\u2572') for i in range(50*24)))3. One‑line love message (ASCII art):
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 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))4. One‑line turtle graphics:
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)]))The post invites readers to share their own exciting one‑line Python creations.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.