来源:http://www.techug.com/post/what-can-a-line-of-python-code-do.html
首先你要了解一下Python之禅,一行代码输出“The Zen of Python”:- python -c "import this""""The 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 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!"""
复制代码 从“The Zen of Python”也能看出,Python倡导Beautiful、Explicit、Simple等原则,当然我们接下来要介绍的一行Python能实现哪些好玩的功能,可能和Explicit原则相违背。
如果你有其他这方面的小例子,也欢迎评论,我会加到文章中,文章也许会长期更新。
[h2]1. 一行代码启动一个Web服务[/h2]- python -m SimpleHTTPServer 8080 # python2python3 -m http.server 8080 # python3
复制代码
[h2][/h2][h2]2. 一行代码实现变量值互换[/h2][h2]3. 一行代码解决FizzBuzz问题[/h2]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 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)]
复制代码 [h2]13. 一行代码实现求解2的1000次方的各位数之和[/h2]- print(sum(map(int, str(2**1000))))
复制代码 推荐阅读
在阿里“解放”鉴黄师是一种怎样的体验
3 个适合新人上手的Python项目
不读研,没出路?全国最疯狂考研地区榜
一个牛逼的 Python 调试工具
8 行代码用Python画一个中国地图
喜欢就点击“在看”吧! |
|