加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

1 行Python代码能干哪些事,这 13个你知道吗?

发布时间:2019-05-11 14:46:02 所属栏目:优化 来源:编程python新视野
导读:副标题#e# 首先你要了解一下Python之禅,一行代码输出The Zen of Python: python -c 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
副标题[/!--empirenews.page--]

 1 行Python代码能干哪些事,这 13个你知道吗?

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

  • python -c "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!
  • """

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

如果你有其他这方面的小例子,也欢迎评论,我会加到文章中,文章也许会长期更新。

1. 一行代码启动一个Web服务

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

2. 一行代码实现变量值互换

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

3. 一行代码解决FizzBuzz问题

FizzBuzz问题:打印数字1到100, 3的倍数打印“Fizz”, 5的倍数打印“Buzz”, 既是3又是5的倍数的打印“FizzBuzz”

  1. for x in range(1, 101): print("fizz"[x % 3 * 4:]+"buzz"[x % 5 * 4:] or x) 

4. 一行代码输出特定字符”Love”拼成的心形

  1. 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 <= 0 else ) for x in range(-30, 30)]) for y in range(30, -30, -1)])) 

5. 一行代码输出Mandelbrot图像

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

  1. 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)) < 2 else for x in range(-80, 20)]) for y in range(-20, 20)])) 

6. 一行代码打印九九乘法表

  1. 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之间的素数(两个版本)

  1. 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))])) 
  2. print( .join([str(item) for item in filter(lambda x: all(map(lambda p: x % p != 0, range(2, x))), range(2, 101))])) 

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读