python 30个技巧、小贴士(3)

21. 在交互式shell中使用_(下划线运算符)

你可以通过下划线运算符获取上一个表达式的结果,例如在 IPython 中,你可以这样操作:

In [1]: 3 * 3
Out[1]: 9In [2]: _ + 3
Out[2]: 12

Python Shell 中也可以这样使用。另外,在 IPython shell 中,你还可以通过 Out[n] 获取表达式 In[n] 的值。例如,在如上示例中,Out[1] 将返回数字9。

22. 快速创建Web服务器

你可以快速启动一个Web服务,并提供当前目录的内容:

python3 -m http.server

当你想与同事共享某个文件,或测试某个简单的HTML网站时,就可以考虑这个方法。

23. 多行字符串

虽然你可以用三重引号将代码中的多行字符串括起来,但是这种做法并不理想。所有放在三重引号之间的内容都会成为字符串,包括代码的格式,如下所示。

我更喜欢另一种方法,这种方法不仅可以将多行字符串连接在一起,而且还可以保证代码的整洁。唯一的缺点是你需要明确指定换行符。

s1 = """Multi line strings can be put
        between triple quotes. It's not ideal
        when formatting your code though"""

print (s1)
# Multi line strings can be put
#         between triple quotes. It's not ideal
#         when formatting your code though

s2 = ("You can also concatenate multiple\n" +
        "strings this way, but you'll have to\n"
        "explicitly put in the newlines")

print(s2)
# You can also concatenate multiple
# strings this way, but you'll have to
# explicitly put in the newlines
24. 条件赋值中的三元运算符

这种方法可以让代码更简洁,同时又可以保证代码的可读性:

[on_true] if [expression] else [on_false]
示例如下:

x = "Success!" if (y == 2) else "Failed!"
25. 统计元素的出现次数

你可以使用集合库中的 Counter 来获取列表中所有唯一元素的出现次数,Counter 会返回一个字典:

from collections import Counter

mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
c = Counter(mylist)
print(c)
# Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2})

# And it works on strings too:
print(Counter("aaaaabbbbbccccc"))
# Counter({'a': 5, 'b': 5, 'c': 5})
26. 比较运算符的链接

你可以在 Python 中将多个比较运算符链接到一起,如此就可以创建更易读、更简洁的代码:

x = 10

# Instead of:
if x > 5 and x < 15:
    print("Yes")
# yes

# You can also write:
if 5 < x < 15:
    print("Yes")
# Yes
27. 添加颜色

在这里插入图片描述

你可以通过 Colorama,设置终端的显示颜色:

from colorama import Fore, Back, Style

print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
28. 日期的处理

python-dateutil 模块作为标准日期模块的补充,提供了非常强大的扩展,你可以通过如下命令安装:

pip3 install python-dateutil 

你可以利用该库完成很多神奇的操作。在此我只举一个例子:模糊分析日志文件中的日期:

from dateutil.parser import parse

logline = 'INFO 2020-01-01T00:00:01 Happy new year, human.'
timestamp = parse(log_line, fuzzy=True)
print(timestamp)
# 2020-01-01 00:00:01

你只需记住:当遇到常规 Python 日期时间功能无法解决的问题时,就可以考虑 python-dateutil !

29.整数除法

在 Python 2 中,除法运算符(/)默认为整数除法,除非其中一个操作数是浮点数。因此,你可以这么写:

# Python 2
5 / 2 = 2
5 / 2.0 = 2.5
在 Python 3 中,除法运算符(/)默认为浮点除法,而整数除法的运算符为 //。因此,你需要这么写:

Python 3
5 / 2 = 2.5
5 // 2 = 2

这项变更背后的动机,请参阅 PEP-0238(https://www.python.org/dev/peps/pep-0238/)。

30. 通过chardet 来检测字符集

你可以使用 chardet 模块来检测文件的字符集。在分析大量随机文本时,这个模块十分实用。安装方法如下:

pip install chardet

安装完成后,你就可以使用命令行工具 chardetect 了,使用方法如下:

chardetect somefile.txt
somefile.txt: ascii with confidence 1.0

猜你喜欢

转载自blog.csdn.net/weixin_42464956/article/details/107533454