程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

What insane functions can a line of Python code achieve? (4 cases)

編輯:Python

I have 109 Open your head CT The CT images of , I'm going to use these pictures to try the three-dimensional reconstruction of the head . One of the basic work , Is to read out these picture data , Organize into a three-dimensional data structure ( It's actually four-dimensional , Because every pixel has RGBA Four channels ).

picture

This data structure , Naturally numpy Of ndarray object , I'm used to reading image files PIL. therefore , Two modules need to be imported :

import numpy as npfrom PIL import Image

Next , I put... In one line of code 109 I read a picture 109x256x256x4 Of numpy Array , Time consuming 172 millisecond :

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 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)

I write this code in one line , But there is no sense of obscurity and difficulty , Still as beautiful as poetry 、 As popular as natural language !

That moment , I have a big hole in my head , really want to know python What can experts do with just one line of code ? Of course , The qualification is that you cannot reference a custom module , You can use built-in modules or common third-party modules . The Internet search , Finding this problem seems to be python Exclusive question , It's hard for other languages to do anything with one line of code . I know there is an article called 《 a line Python What insane functions can be realized ?》 's post , Its mirror image paste only java And js Of , Click in and find out , and python Is not a concept at all .

Sort out the content of Zhihu's last article , Quite interesting , Share with you .

1. One line code 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)]))
picture

2. One line code printing maze

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

3. A line of code expresses 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)]))
picture

4. A line of code to print 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)]))
picture

you are here python What exciting functions have you realized with one line of code in the process of use ?


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved