美文网首页视觉艺术初学者
19个 python 的最佳实践小技巧,你学会了吗

19个 python 的最佳实践小技巧,你学会了吗

作者: 淺儚 | 来源:发表于2020-04-21 20:38 被阅读0次

相信大家在学习Python的过程中,可能会遇到一些坎儿,也可能缺乏一些简洁的解决方法,下面我给大家分享一些实用的小技巧,也许对大家会有帮助

1.列表推导式

你可以利用列表推导式,避免使用循环填充列表时的繁琐。列表推导式的基本语法如下:

[ expression for item in list if conditional ]

举一个基本的例子:用一组有序数字填充一个列表:

mylist = [i for i in range(10)]

print(mylist)

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

由于可以使用表达式,所以你也可以做一些算术运算:

squares = [x**2 for x in range(10)]

print(squares)

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

甚至可以调用外部函数:

def some_function(a):

return (a + 5) / 2

my_formula = [some_function(i) for i in range(10)]

print(my_formula)

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

最后,你还可以使用 ‘if’ 来过滤列表。在如下示例中,我们只保留能被2整除的数字:

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

print(filtered)

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

2. 检查对象使用内存的状况

你可以利用 sys.getsizeof 来检查对象使用内存的状况:

import sys

mylist = range(0, 10000)

print(sys.getsizeof(mylist))

# 48

等等,为什么这个巨大的列表仅包含48个字节?

因为这里的 range 函数返回了一个类,只不过它的行为就像一个列表。在使用内存方面,range 远比实际的数字列表更加高效。

你可以试试看使用列表推导式创建一个范围相同的数字列表:

import sys

myreallist = [x for x in range(0, 10000)]

print(sys.getsizeof(myreallist))

# 87632

3. 返回多个值

Python 中的函数可以返回一个以上的变量,而且还无需使用字典、列表或类。如下所示:

def get_user(id):

# fetch user from database

# ....

return name, birthdate

name, birthdate = get_user(4)

如果返回值的数量有限当然没问题。但是,如果返回值的数量超过3个,那么你就应该将返回值放入一个(数据)类中。

4. 使用数据类

Python从版本3.7开始提供数据类。与常规类或其他方法(比如返回多个值或字典)相比,数据类有几个明显的优势:

数据类的代码量较少

你可以比较数据类,因为数据类提供了 __eq__ 方法

调试的时候,你可以轻松地输出数据类,因为数据类还提供了 __repr__ 方法

数据类需要类型提示,因此可以减少Bug的发生几率

数据类的示例如下:

from dataclasses import dataclass

@dataclass

class Card:

rank: str

suit: str

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

print(card == card)

# True

print(card.rank)

# 'Q'

print(card)

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

详细的使用指南请点击这里(https://realpython.com/python-data-classes/)。

5. 交换变量

如下的小技巧很巧妙,可以为你节省多行代码:

a = 1

b = 2

a, b = b, a

print (a)

# 2

print (b)

# 1

6. 合并字典(Python 3.5以上的版本)

从Python 3.5开始,合并字典的操作更加简单了:

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

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

merged = { **dict1, **dict2 }

print (merged)

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

如果 key 重复,那么第一个字典中的 key 会被覆盖。

这里是本人整理的一些python学习资料,感兴趣的可以来看看

7. 字符串的首字母大写

如下技巧真是一个小可爱:

mystring = "10 awesome python tricks"

print(mystring.title)

'10 Awesome Python Tricks'

8. 将字符串分割成列表

你可以将字符串分割成一个字符串列表。在如下示例中,我们利用空格分割各个单词:

mystring = "The quick brown fox"

mylist = mystring.split(' ')

print(mylist)

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

9. 根据字符串列表创建字符串

与上述技巧相反,我们可以根据字符串列表创建字符串,然后在各个单词之间加入空格:

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

mystring = " ".join(mylist)

print(mystring)

# 'The quick brown fox'

你可能会问为什么不是 mylist.join(" "),这是个好问题!

根本原因在于,函数 String.join 不仅可以联接列表,而且还可以联接任何可迭代对象。将其放在String中是为了避免在多个地方重复实现同一个功能。

10. 列表切片

列表切片的基本语法如下:

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 stringstoo. In Python,

# you can treat a string like a list of

# letters:

mystring = "abcdefdn nimt"[::2]

print(mystring)

# 'aced it'

11. 反转字符串和列表

你可以利用如上切片的方法来反转字符串或列表。只需指定 step 为 -1,就可以反转其中的元素:

revstring = "abcdefg"[::-1]

print(revstring)

# 'gfedcba'

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

print(revarray)

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

12. map

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 替代某处的循环。

13. 获取列表或字符串中的唯一元素

如果你利用函数 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'}

14. 查找出现频率最高的值

你可以通过如下方法查找出现频率最高的值:

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

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

# 4

你能看懂上述代码吗?想法搞明白上述代码再往下读。

没看懂?我来告诉你吧:

max 会返回列表的最大值。参数 key 会接受一个参数函数来自定义排序,在本例中为 test.count。该函数会应用于迭代对象的每一项。

test.count 是 list 的内置函数。它接受一个参数,而且还会计算该参数的出现次数。因此,test.count(1) 将返回2,而 test.count(4) 将返回4。

set(test) 将返回 test 中所有的唯一值,也就是 {1, 2, 3, 4}。

因此,这一行代码完成的操作是:首先获取 test 所有的唯一值,即{1, 2, 3, 4};然后,max 会针对每一个值执行 list.count,并返回最大值。

这一行代码可不是我个人的发明。

15. 快速创建Web服务器

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

python3 -m http.server

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

16. 多行字符串

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

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

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

17. 条件赋值中的三元运算符

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

[on_true] if [expression] else [on_false]

示例如下:

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

18. 统计元素的出现次数

你可以使用集合库中的 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 stringstoo:

print(Counter("aaaaabbbbbccccc"))

# Counter({'a': 5, 'b': 5, 'c': 5})

19. 比较运算符的链接

你可以在 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

好了,以上便是我分享给大家的一些有关Python的小技巧,希望在学习python的过程中能对大家有帮助,喜欢的帮忙点个赞,谢谢大家了,需要学习资料的可以给我留言或者私信我哦。

相关文章

网友评论

    本文标题:19个 python 的最佳实践小技巧,你学会了吗

    本文链接:https://www.haomeiwen.com/subject/ewzpihtx.html