短短几行Python代码能干哪些事?来看看这几个小示例。

258 阅读4分钟
原文链接: bingyishow.top

前言

首先需要了解一下Python之禅,一行代码输出“The Zen of Python”

>>> import this
The Zen of Python, by Tim Peters

Beautiful 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 of ambiguity, refuse the temptation to 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 the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

译文如下:

Python 之禅, by Tim Peters

优美胜于丑陋(Python 以编写优美的代码为目标) 
明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似) 
简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现) 
复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁) 
扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套) 
间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题) 
可读性很重要(优美的代码是可读的) 
即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上) 
不要包容所有错误,除非你确定需要这样做(精准地捕获异常,不写except:pass风格的代码) 
当存在多种可能,不要尝试去猜测 
而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法) 
虽然这并不容易,因为你不是 Python 之父(这里的 Dutch 是指 Guido) 
做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量) 
如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然(方案测评标准) 
命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)

从“The Zen of Python”也能看出,Python倡导Beautiful、Explicit、Simple等原则,当然我们接下来要介绍的一行Python能实现哪些好玩的功能,可能和Explicit原则相违背。

一行代码启动一个Web服务

python -m SimpleHTTPServer 8080  # python2
python3 -m http.server 8080  # python3

1

一行代码实现变量值互换

a, b = 1, 2; a, b = b, a

一行代码解决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)

一行代码输出特定字符”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 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))

2

一行代码输出Mandelbrot图像

Mandelbrot图像:图像中的每个位置都对应于公式N=x+y*i中的一个复数

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

3

一行代码打印九九乘法表

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

4

一行代码计算出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))]))

5

一行代码输出斐波那契数列

print([x[0] for x in [(a[i][0], a.append([a[i][6], a[i][0]+a[i][7]])) for a in ([[1, 1]], ) for i in range(30)]])

一行代码实现快排算法

qsort = lambda arr: len(arr) > 1 and qsort(list(filter(lambda x: x <= arr[0], arr[1:]))) + arr[0:1] + qsort(list(filter(lambda x: x > arr[0], arr[1:]))) or arr

一行代码解决八皇后问题

[__import__('sys').stdout.write('\n'.join('.' * i + 'Q' + '.' * (8-i-1) for i in vec) + "\n========\n") 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)))]

6

一行代码实现数组的flatten功能

将多维数组转化为一维

flatten = lambda x: [y for l in x for y in flatten(l)] if isinstance(x, list) else [x]

一行代码实现list

有点类似与上个功能的反功能

array = lambda x: [x[i:i+3] for i in range(0, len(x), 3)]

一行代码实现求解2的1000次方的各位数之和

print(sum(map(int, str(2**1000))))
引自:推酷