bd@atyun.com
我终于找到了一个充分的借口可以在我的文章中显示猫猫了,哈哈!当然,你也可以利用它来显示图片。首先你需要安装 Pillow,这是一个 Python 图片库的分支:
pip3 install Pillow
接下来,你可以将如下图片下载到一个名叫 kittens.jpg 的文件中:
然后,你就可以通过如下 Python 代码显示上面的图片:
from PIL import Image im = Image.open("kittens.jpg") im.show() print(im.format, im.size, im.mode) # JPEG (1920, 1357) RGB
Pillow 还有很多显示该图片之外的功能。它可以分析、调整大小、过滤、增强、变形等等。完整的文档,请点击这里(https://pillow.readthedocs.io/en/stable/)。
Python 有一个自带的函数叫做 map(),语法如下:
map(function, something_iterable)
所以,你需要指定一个函数来执行,或者一些东西来执行。任何可迭代对象都可以。在如下示例中,我指定了一个列表:
def upper(s): return s.upper() mylist = list(map(upper, ['sentence', 'fragment'])) print(mylist) # ['SENTENCE', 'FRAGMENT'] # Convert a string representation of # a number into a list of ints. list_of_ints = list(map(int, "1234567"))) print(list_of_ints) # [1, 2, 3, 4, 5, 6, 7]
你可以仔细看看自己的代码,看看能不能用 map() 替代某处的循环。
如果你利用函数 set() 创建一个集合,就可以获取某个列表或类似于列表的对象的唯一元素:
mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6] print (set(mylist)) # {1, 2, 3, 4, 5, 6} # And since a string can be treated like a # list of letters, you can also get the # unique letters from a string this way: print (set("aaabbbcccdddeeefff")) # {'a', 'b', 'c', 'd', 'e', 'f'}
你可以通过如下方法查找出现频率最高的值:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] print(max(set(test), key = test.count)) # 4
你能看懂上述代码吗?想法搞明白上述代码再往下读。
没看懂?我来告诉你吧:
因此,这一行代码完成的操作是:首先获取 test 所有的唯一值,即{1, 2, 3, 4};然后,max 会针对每一个值执行 list.count,并返回最大值。
这一行代码可不是我个人的发明。
你可以创建自己的进度条,听起来很有意思。但是,更简单的方法是使用 progress 包:
pip3 install progress
接下来,你就可以轻松地创建进度条了:
from progress.bar import Bar bar = Bar('Processing', max=20) for i in range(20): # Do some work bar.next() bar.finish()
你可以通过下划线运算符获取上一个表达式的结果,例如在 IPython 中,你可以这样操作:
In [1]: 3 * 3 Out[1]: 9In [2]: _ + 3 Out[2]: 12
Python Shell 中也可以这样使用。另外,在 IPython shell 中,你还可以通过 Out[n] 获取表达式 In[n] 的值。例如,在如上示例中,Out[1] 将返回数字9。
你可以快速启动一个Web服务,并提供当前目录的内容:
python3 -m http.server
当你想与同事共享某个文件,或测试某个简单的HTML网站时,就可以考虑这个方法。
虽然你可以用三重引号将代码中的多行字符串括起来,但是这种做法并不理想。所有放在三重引号之间的内容都会成为字符串,包括代码的格式,如下所示。
我更喜欢另一种方法,这种方法不仅可以将多行字符串连接在一起,而且还可以保证代码的整洁。唯一的缺点是你需要明确指定换行符。
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
这种方法可以让代码更简洁,同时又可以保证代码的可读性:
[on_true] if [expression] else [on_false]
示例如下:
x = "Success!" if (y == 2) else "Failed!"
你可以使用集合库中的 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})
你可以在 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
你可以通过 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')
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 !
在 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/)。
你可以使用 chardet 模块来检测文件的字符集。在分析大量随机文本时,这个模块十分实用。安装方法如下:
pip install chardet
安装完成后,你就可以使用命令行工具 chardetect 了,使用方法如下:
chardetect somefile.txt somefile.txt: ascii with confidence 1.0
你也可以在编程中使用该库,完整的文档请点击这里(https://chardet.readthedocs.io/en/latest/usage.html)。
原文链接:https://towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
要发表评论,您必须先登录。