几个小例子告诉你, 一行Python代码能做什么

首先你要了解一下python之禅,一行代码输出“the zen of python”:
python -c importthisthe zen of python, by tim petersbeautiful is better than ugly.explicit is better than implicit.simple is better than complex.complex is better than complicated.flat is better than nested.sparse is better than dense.readability counts.special cases aren't special enough to break the rules.although practicality beats purity.errors should never pass silently.unless explicitly silenced.in the face ofambiguity, refuse thetemptationto guess.there should be one-- and preferably only one --obvious way to do it.although that way may not be obvious at first unless you're dutch.now is better than never.although never is often better than *right* now.if theimplementationis hard toexplain, it's a bad idea.if theimplementationis easy toexplain, it may be a good idea.namespaces are one honking great idea -- let's do more of those!
从“the zen of python”也能看出,python倡导beautiful、explicit、simple等原则,当然我们接下来要介绍的一行python能实现哪些好玩的功能,可能和explicit原则相违背。
(1)一行代码启动一个web服务
python -m simplehttpserver 8080 # python2python3 -m http.server 8080 #python3
(2)一行代码实现变量值互换
a, b = 1, 2; a, b = b, a
(3)一行代码解决fizzbuzz问题:
fizzbuzz问题:打印数字1到100, 3的倍数打印“fizz”, 5的倍数打印“buzz”,既是3又是5的倍数的打印“fizzbuzz”
for x in range(1, 101): print(fizz[x % 3 * 4:]+buzz[x % 5 * 4:] or x)
(4)一行代码输出特定字符love拼成的心形
print(' '.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
(5)一行代码输出mandelbrot图像
mandelbrot图像:图像中的每个位置都对应于公式n=x+y*i中的一个复数
print(' '.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))
(6)一行代码打印九九乘法表
print(' '.join([' '.join(['%s*%s=%-2s' % (y, x, x*y) for y in range(1, x+1)]) for x in range(1, 10)]))
(7)一行代码计算出1-100之间的素数(两个版本)
print(' '.join([str(item) for item in filter(lambda x: not [x % i for i in range(2, x) if x % i == 0], range(2, 101))]))print(' '.join([str(item) for item in filter(lambda x: all(map(lambda p: x % p != 0, range(2, x))), range(2, 101))]))
(8)一行代码输出斐波那契数列
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(30)]])
(9)一行代码实现快排算法
qsort =lambda arr: len(arr) > 1 and qsort(list(filter(lambda x: x arr[0], arr[1:]))) or arr
(10)一行代码解决八皇后问题
[__import__('sys').stdout.write(' '.join('.' * i + 'q' + '.' * (8-i-1) for i in vec) + ======== ) for vec in __import__('itertools').permutations(range(8)) if 8 == len(set(vec[i]+i for i in range(8))) == len(set(vec[i]-i for i in range(8)))]
(11)一行代码实现数组的flatten功能:将多维数组转化为一维
flatten = lambda x: [y for l in x for y in flatten(l)] if isinstance(x, list) else [x]
(12)一行代码实现list,有点类似与上个功能的反功能
array = lambda x: [x[i:i+3] for i in range(0, len(x), 3)]
(13)一行代码实现求解2的1000次方的各位数之和