Skip to content

Files

Latest commit

b03d156 · Nov 20, 2019

History

History
92 lines (56 loc) · 1.33 KB

93.md

File metadata and controls

92 lines (56 loc) · 1.33 KB

Python 的有趣技巧

原文: https://pythonspot.com/fun-tricks-with-python/

启动简单的 HTTP Web 服务器

可以在几秒钟内启动简单的 HTTP 服务器。

python -m SimpleHTTPServer

对于 Python3:

python -m http.server

启动后,您可以打开 http://127.0.0.1:8000/。 浏览器将向您显示目录的内容。

有趣的文字

尝试以下语句来显示蒂姆·彼得斯的诗。

import this

XKCD 网络漫画

您可以使用以下方法在 XKCD 上打开漫画:

import antigravity

使用zip合并数组

您可以使用以下命令压缩两个数组:

b = [[1, 2, 3, 4], [6, 5, 4, 3]]
zip(*b)
[(1, 6), (2, 5), (3, 4), (4, 3)]

反转列表

要反转列表,可以实现一个功能。 但是,如果已经实施,为什么还要麻烦解决呢?

b = [1,2,3,4,5]
b.reverse()
print b
[5, 4, 3, 2, 1]

反转字符串

可以使用以下方法来代替创建反向字符串的方法:

s = "Hello world"
s = s[::-1]
print s
dlrow olleH

交换变量

您无需定义临时变量即可交换为 Python 中的变量:

a = 1
b = 3
b,a = a,b
print a
print b
1

如果您知道任何提示或技巧,请发表评论。 :-)