可能大家在網上已經看過類似的python單行代碼可以實作的功能,比如:
九九乘法表:
print(’ ‘.join([’ ‘.join([‘%s*%s=%-2s’%(y,x,x*y)for y in range(1,x+1)]) for x in range(1,10)]))
或者輸出前100項斐波那契數列的值:
print([x[0] for x in [ (a[i][0], a.append((a[i][1], a[i][0]+a[i][1]))) for a in ([[1,1]] ) for i in range(100) ]])
嗯,這些都可以做到,那麼下面的這些炫酷的代碼,更值得一看!
單線迷宮(cmd下輸入):
python -c “while 1:import random;print(random.choice(‘|| __’), end=”)”
emmmm,這個可能比較抽象,那麼試試将裡面的字元換一下,比如下面這個代碼
python -c “while 1:import random;print(random.choice(‘╱╲’), end=”)”
這個迷宮效果還可以吧!
猜數字
好多的教程中都有這個小案例,那麼你用了幾行呢?試試下面這個
python -c “import random;n=random.randint(1,99);[(lambda a:print(‘Y’ if a==n else ‘H’ if a>n else ‘L’))(int(input())) for i in range(6)]”
是的,你沒有看錯,一行代碼可以實作這個功能!
100英尺高爾夫
參照了“憤怒的小鳥”,目标是讓高爾夫剛好落到100英尺處,不多不少!
import math as m;a,v=eval(input());[print(‘%03d’%x+’ ‘*m.floor(0.5+x*m.tan(a)-x*x/(v*m.cos(a)))+’o’) for x in range(102)]
需要輸入2個參數,也就是高爾夫的角度和速度!
最後
這些代碼使用的大多數技術應該看起來很熟悉:
清單解析,lambda表達式和随機整數,通過幾個函數的組合,可以寫出很酷的代碼!
大家也可以來我的公衆号python入門,大家一起交流學習!