欢迎来到爱学习爱分享,在这里,你会找到许多有趣的技术 : )

[译] 30 个 Python 最佳实践和技巧,你值得拥有

开发者头条 630℃

全文共8869字,预计学习时长26分钟
来源:Pexels
1. 使用Python3
温馨提示:官方宣布自2020年1月一日起将不再支持Python2这份指南里的大多数例子也只在Python3中适用。如果您还在使用Python2.7,赶快更新吧。如果您使用的是苹果电脑,可以使用Homebrew轻松升级。 2. 检查Python的最低要求版本 您可以直接使用代码来查看Python版本,确保将来不会出现脚本和Python版本不兼容的情况发生。请看示例:

ifnot  sys.version_info > (2, 7):

   # berate your user for running a  10 year

   # python version

elifnot  sys.version_info >= (3, 5):

   # Kindly tell your user (s)he  needs to upgrade

   # because you're using 3.5  features

viewrawcheck_python_version.py hosted with ❤ by GitHub

3. 使用IPython 作者截图 实际上,IPython是一个增强的shell。自动完成功能已足以令人惊叹,但它还有更多功能。我非常喜欢内置的魔术命令。以下是一些例子: · %cd -用于更改当前工作目录· 编辑-打开编辑器,并执行您在关闭编辑器后键入的代码·       %env — 展示当前环境变量·       %pip install [pkgs] — 在交互环境下安装包·       %time 和 %timeit — 计算Python代码的执行时间 另一个有用的功能是引用前一个命令的输出。In和Out是实际的对象。您可以通过使用Out[3]来进行第三个命令的输出。 下载Python命令安装Ipython:

pip3install ipython

4. 列表推导 列表推导可以替换丑陋的用于填充列表的for循环。列表推导的基本语法是:

[expression for item in list if conditional ]

这是一个最基本的例子,使用数字序列填充列表:

mylist = [i for i inrange(10)]

print(mylist)

# [0, 1,  2, 3, 4, 5, 6, 7, 8, 9]

viewrawlist_comprehensions_1.py hostedwith ❤ by GitHub

同时你还可以用这种表达进行数学运算:

squares = [x**2for x inrange(10)]

print(squares)

# [0, 1,  4, 9, 16, 25, 36, 49, 64, 81]

viewrawlist_comprehensions_2.py hostedwith ❤ by GitHub

甚至额外创建一个新函数:

defsome_function(a):

    return (a +5) /2

my_formula  = [some_function(i) for i inrange(10)]

print(my_formula)

# [2, 3,  3, 4, 4, 5, 5, 6, 6, 7]

viewrawlist_comprehensions_3.py hostedwith ❤ by GitHub

最终,你可以使用“if”来过滤列表。在这个例子中,只保留了能被2整除的值

filtered  = [i for i inrange(20) if i%2==0]

print(filtered)

# [0, 2,  4, 6, 8, 10, 12, 14, 16, 18]

viewrawlist_comprehensions_4.py hosted with ❤ by GitHub

5.检查对象的内存使用 使用 sys.getsizeof(),可以检查对象的记忆内存:

import sys

mylist =range(0, 10000)

print(sys.getsizeof(mylist))

# 48

viewrawcheck_memory_usage_1.py hostedwith ❤ by GitHub

为什么这样一个巨大的列表仅占48字节内存? 这是因为range函数返回的类只表现为一个列表。范围比使用实际的数字列表更节省内存。 你可以自己使用列表推导创建同一范围内的实际数字列表:

import sys

myreallist  = [x for x inrange(0, 10000)]

print(sys.getsizeof(myreallist))

# 87632

viewrawcheck_memory_usage_2.py hosted with ❤ by GitHub

6. 返回多个值 来源:Pexels
Python中的函数可以返回多个变量,而无需字典、列表或类。它的工作原理如下:

defget_user(id):

    # fetch user from database

    # ....

    return name,  birthdate

name,  birthdate = get_user(4)

viewrawreturn_multiple_variables.py hosted with ❤ by GitHub

对于有限数量的返回值,这是可以的。但是任何超过3个值的内容都应该放到一个(data)类中。 7. 使用数据类 从3.7版开始,Python提供了数据类。与常规类或其他替代方法(如返回多个值或字典)相比,有几个优点: ·  一个数据类需要最少的代码·  可以比较数据类,因为已经实现了_eq__·  您以轻易打印一个数据类进行调试,因为也实现了_repr__·  数据类需要类型提示,减少了出错几率 下面是一个数据类的例子:

from  dataclasses import dataclass

@dataclass

classCard:

    rank: str

    suit: str

card = Card("Q", "hearts")

print(card == card)

# True

print(card.rank)

# 'Q'

print(card)

Card(rank='Q', suit='hearts'

viewrawdataclass.py hosted with ❤ by GitHub

点击这里查看高阶指南 。 8. 变量交换 一个小技巧就可以省略数行代码。

a =1

b =2

a, b = b, a

print (a)

# 2

print (b)

# 1

viewrawin_place_variable_swapping.py hosted with ❤ by GitHub

9. 合并字典(Python3.5+) 自Python3.5 以来,合并字典更为简便

dict1 = { 'a': 1, 'b': 2 }

dict2 = { 'b': 3, 'c': 4 }

merged = { **dict1, **dict2 }

print  (merged)

# {'a':  1, 'b': 3, 'c': 4}

viewrawmerging_dicts.py hostedwith ❤ by GitHub

如果有重叠的值,来自第一个字典的值将被覆盖。 10. 标题大小写 这只是其中一种有趣的玩法:

mystring  ="10  awesome python tricks"

print(mystring.title())

'10  Awesome Python Tricks'

viewrawstring_to_titlecase.py hosted with ❤ by GitHub

11. 切割字符串至列表 来源:Pexels
可以将字符串拆分为字符串列表。在下例中,根据空格切割

mystring  ="The  quick brown fox"

mylist =  mystring.split(' ')

print(mylist)

#  ['The', 'quick', 'brown', 'fox']

viewrawstring_to_list.py hosted with ❤ by GitHub

12. 从字符串列表中创建一个字符串 与上一个技巧正好相反,在本例中,从字符串列表中创建一个字符串,并在单词间输入空格:

mylist = ['The', 'quick', 'brown', 'fox']

mystring  ="  ".join(mylist)

print(mystring)

# 'The  quick brown fox'

viewrawlist_to_string.py hostedwith ❤ by GitHub

你或许在想为什么不用mylist.join(” “) ,好问题! 归根结底,String.join()函数不仅可以连接列表,还可以连接任何可迭代的列表。将它放在String中会阻止在多个位置实现相同的功能。 13. 表情 表情要么是欢喜,要么是讨厌,这依表情而定。更重要的是,这在分析社交媒体数据时尤其有用。 首先,下载表情模块

pip3install emoji

下载完之后,就可以按如下操作:

import emoji

result =  emoji.emojize('Python is :thumbs_up:')

print(result)

#  'Python is ????'

# You  can also reverse this:

result =  emoji.demojize('Python is ????')

print(result)

#  'Python is :thumbs_up:'

viewrawemoji.py hosted with ❤ by GitHub

访问表情包页面查看更多描述和示例 14. 制作列表切片 列表切片的句法:

a[start:stop:step]

Start, stop 和 step 都是可选项. 如果未设置,默认值会是 ·       Start值为0·       End为字符串末尾·       step值为1 以下是一个例子:

# We can  easily create a new list from

# the  first two elements of a list:

first_two  = [1, 2, 3, 4, 5][0:2]

print(first_two)

# [1, 2]

# And if  we use a step value of 2,

# we can  skip over every second number

# like  this:

steps = [1, 2, 3, 4, 5][0:5:2]

print(steps)

# [1, 3,  5]

# This  works on strings too. In Python,

# you  can treat a string like a list of

#  letters:

mystring  ="abcdefdn  nimt"[::2]

print(mystring)

# 'aced  it'

viewrawlist_slicing.py hosted with ❤ by GitHub

15. 反转字符串和列表 使用上面的切片符号来反转字符串或列表。通过使用负的步进值-1,从而反转元素:

revstring  ="abcdefg"[::-1]

print(revstring)

#  'gfedcba'

revarray  = [1, 2, 3, 4, 5][::-1]

print(revarray)

# [5, 4,  3, 2, 1]

viewrawreversing_stuff.py hosted with ❤ by GitHub

16. 展示小猫 首先,安装Pillow(Python图像库的一个分支):

pip3install Pillow

下载这张图片,并把它命名为kittens.jpg:
图源 TheDigitalArtist  Pixabay 可以使用以下代码来显示Python代码中的图像: 或者直接使用IPython:

fromPILimport Image

im =  Image.open("kittens.jpg")

im.show()

print(im.format,  im.size, im.mode)

# JPEG  (1920, 1357) RGB

viewrawpillow.py hosted with ❤ by GitHub

除了显示图像,Pillow还可以分析、调整大小、过滤、增强、变形等等。有关它的所有特性,请参阅文档 17. 使用map() Python的一个内置函数是map()。map()的语法是: map(function, something_iterable) 给定一个要执行的函数,和一些要运行的变量。它可以是任何可迭代的元素。在下面的例子中,我将使用一个列表。

defupper(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]

viewrawmap.py hostedwith ❤ by GitHub

看看自己的代码,看看是否可以在某处使用map()而不是循环! 18. 从列表和字符串中提取独特元素 通过使用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'}

viewrawset.py hosted with ❤ by GitHub

19. 找到频率出现最高的值 查找列表或字符串中最常出现的值:

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]

print(max(set(test), key=  test.count))

# 4

viewrawmost_frequent.py hostedwith ❤ by GitHub

你明白为什么会这样吗?在继续阅读之前,试着自己找出答案。还没尝试吗?我要告诉你答案了。 ·        max()将返回列表中的最大值。key参数接受单个参数函数来定制排序顺序,在本例中,它是test.count。该函数应用于iterable上的每个项目。·       测试。count是一个内置的列表函数。它接受一个参数,并将计算该参数的出现次数。因此test.count(1)将返回2,而test.count(4)将返回4。·        set(test)返回test中所有的唯一值,因此{1,2,3,4} 因此,我们在这一行代码中所做的就是获取test的所有唯一值,即{1,2,3,4}。接下来,max将应用list.count 函数,并返回最大值。 20. 创建一个进度条 创建自己的进度条,这很有趣。但是使用进度包更快:

pip3install progress

现在可以花费更少的时间创建进度条

from  progress.bar import Bar

bar = Bar('Processing', max=20)

for i inrange(20):

    # Do some work

    bar.next()

bar.finish()

viewrawprogress_bar.py hostedwith ❤ by GitHub 21. 在交互式窗口中使用_ 来源:Pexels
可以用下划线运算符得到最后一个表达式的结果,例如,在IPython中,如下所示:

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

这也适用于Pythonshell。此外,IPython shell允许使用Out[n]来获取[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

viewrawmultiline_strings.py hosted with ❤ by GitHub

24.三元运算符,用于条件赋值 这是使代码兼具简洁性与可读性的另一种方法:[on_true] if [expression] else[on_false] 例子:

x = "Success!" if (y== 2) else "Failed!"

25. 计算频率 使用集合库中的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})

viewrawcounter.py hosted with ❤ by GitHub

26. 链接比较运算符 在Python中链接比较运算符,以创建更易读和简洁的代码:

x =10

#  Instead of:

if x >5and x <15:

    print("Yes")

# yes

# You  can also write:

if5< x <15:

    print("Yes")

# Yes

viewrawchaining_comparisons.py hosted with ❤ by GitHub

27. 添加一些颜色 截图 Jonathan Hartley 源Colorama 使用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')

viewrawcolorama.py hosted with ❤ by GitHub

28. 添加日期 python-dateutil模块提供了对标准datetime模块的强大扩展。 通过以下方式安装:

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

viewrawdateutil.py hosted with ❤ by GitHub

只需记住:常规的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

30. 使用chardet进行字符集检测 来源:Pexels
使用chardet模块来检测文件的字符集。在分析大量随机文本时,这很有用。
安装方式:

pip install chardet

现在,有了一个名为chardetect的额外命令行工具,可以像这样使用:

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

以上就是2020年30条最佳的代码技巧。我希望您能像享受创建列表一样,享受这些内容。如果您有任何意见,请随时发表评论! 来源:Pexels

推荐阅读专题

留言点赞发个朋友圈我们一起分享AI学习与发展的干货
编译组:李韵帷、吴亚芳相关链接:https://towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5

如转载,请后台留言,遵守转载规范
推荐文章阅读
ACL2018论文集50篇解读EMNLP2017论文集28篇论文解读2018年AI三大顶会中国学术成果全链接ACL2017论文集:34篇解读干货全在这里10篇AAAI2017经典论文回顾
长按识别二维码可添加关注读芯君爱你

转载请注明:爱学习爱分享 » [译] 30 个 Python 最佳实践和技巧,你值得拥有

喜欢 (0)or分享 (0)