Python20个有用的小技巧让你成为更好的python开发者

已收录   阅读次数: 1,112
2021-03-1420:39:00 发表评论
摘要

伯衡君已经学习python四个月了,从网上和自己编程过程中总结了一些经验,这里列出20条,可以让大家成为更好的python开发者,那么都是什么呢?请看这篇文章……

分享至:
Python20个有用的小技巧让你成为更好的python开发者

开篇寄语

伯衡君已经学习python四个月了,从网上和自己编程过程中总结了一些经验,这里列出20条,可以让大家成为更好的python开发者,那么都是什么呢?请看这篇文章。

内容详情

1.python之禅

输入“import this”可以获得python之禅,体会大师级的编程~~

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

2.省略号

Python省略号是三个点的序列。它在常规(非编程)语言中使用了很多。但您可能不知道的是,它也是Python中的有效对象:

>>>...
Ellipsis

它的主要用途似乎是在NumPy中的矩阵切片操作中。但是,您可以将其用作尚未实现的功能中的占位符,而不是像大多数人一样使用pass:

>>>def my_func():
    ... #相当于pass

3.匿名函数

有时,给函数命名是不值得的。例如,当您确定该功能仅使用一次时。对于这种情况,Python向我们提供了匿名函数,也称为lambda函数。

>>> add_five = lambda x: x + 5
>>> add_five(3)
8

当您需要使用函数作为参数时,它会变得更加有趣。在这种情况下,该功能通常仅使用一次。如您所知,map将函数应用于可迭代对象的所有元素。我们可以在调用map时使用lambda:

>>> numbers = [1, 2, 3, 4]
>>> prod_two = map(lambda x: x * 2, numbers)
>>> list(prod_two)
[2, 4, 6, 8]

实际上,这是您经常看到的一种模式。当您需要在可迭代对象的每个元素上应用相对简单的操作时,将map()与lambda函数结合使用既简洁又有效。

4.快捷命名

通常情况下,给参数赋值,需要一行填写一个,但是在python中却有更加方便的方法,比如下面这样:

>>> a,b,c = 20,30,40
>>> a
20
>>> b
30
>>> c
40
>>> [a,*b,c]=[20,30,40,50,60,70]
>>> a
20
>>> c
70
>>> b
[30, 40, 50, 60]

5."string"和“list”便捷翻转

一般翻转“list”是需要用到reversed或者reverse,而翻转“string”则需要先转成“list”再翻转比较麻烦,但是用[::-1]可以快速将“string”和“list”进行翻转:

>>> "123"[::-1]
'321'
>>> [1, 2, 3][::-1]
[3, 2, 1]
>>>

6.交叉赋值

一项巧妙的小技巧,可以节省几行代码:

a = 1
b = 2
a, b = b, a
print (a)
# 2
print (b)
# 1

相比以下的方法,可以节省很多:

>>> a = 1
>>> b = 2
>>> c = a
>>> a = b
>>> b = c
>>> print(a)
2
>>> print(b)
1

7.下划线继承之前结果

你可以在Python REPL中使用下划线操作符来获得最后一个表达式的结果,例如,在Python REPL中,如下所示:

>>> a
3
>>> _ + 2
5

8.用enumerate()将“list”编程“dictionary”在一行

将“list”转换为“dictionary”可以用enumerate()快速转换,只用一行哦。

>>> lst = ["a","b","c","d"]
>>> {x:y for y,x in enumerate(lst)}
{'a': 0, 'b': 1, 'c': 2, 'd': 3}

9.使用title()让每个首字母都大写

写英文标题,肯定是首字母需要大写的,只需要使用title()这个函数,可以轻松搞定,比如下面这个例子:

>>> a = "do you know? the python has already 30 years old!"
>>> a.title()
'Do You Know? The Python Has Already 30 Years Old!'

10.list切片

列表切片的基本语法为:

lst[start:stop:step]

比较简单,看例子就懂了:

>>> [1,3,6,2,87,3,5,74,33,4][0::3]
[1, 2, 5, 4]

11.Ternary Operator

就是if……else写在一行,减少代码输入量,基本样式如下:

>>> "a" if (y == 2) else "b"

如果是if……elif……else也是可以写在一行,基本样式如下:

>>> "a" if (y == 2) else "b" if (y == 3) else "c"

12.嵌套列表推导式

如果expression可以是任何有效的Python表达式,那么它也可以是另一个列表推导。当您要创建矩阵时,这可能会很有用:

>>> [[j for j in range(3)] for i in range(4)]
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

12.检查最小python版本要求

您可以在代码中检查Python版本,以确保您的用户没有使用不兼容的版本运行脚本。使用这个简单的检查:

if not sys.version_info > (2, 7):
  #somethings
elif not sys.version_info >= (3, 5):
  #somethings

13.组合字典

从Python 3.5开始,合并字典变得更容易了。而对于Python 3.9,更是如此!

dicty1 = { 'a': 1, 'b': 2 }
dicty2 = { 'b': 3, 'c': 4 }
merged = { **dicty1, **dicty2 }

print (merged)
# {'a': 1, 'b': 3, 'c': 4}

# Python >= 3.9 only
merged = dicty1 | dicty2

print (merged)
# {'a': 1, 'b': 3, 'c': 4}

14."string"=>"list"隐藏秘密

python中,想要把string转变为list,只需要用到split()函数即可,如下所示:

>>> "a b c".split(" ")
['a', 'b', 'c']

其实,split()还可以控制切割的数量,如下例所示:

>>> "a b c".split(" ",1)
['a', 'b c']

15."@"装饰器

装饰器是围绕函数的包装器,它们以某种方式修改函数的行为。装饰器有很多用例,在使用Flask之类的框架时,您可能已经使用过它们。

让我们创建自己的装饰器;它比您预期的要简单,并且有一天可能会派上用场:

def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner


def percent(func):
    def inner(*args, **kwargs):
        print("%" * 30)
        func(*args, **kwargs)
        print("%" * 30)
    return inner


@star
@percent
def printer(msg):
    print(msg)


printer("Hello")

输出结果如下:

******************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Hello
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
******************************

16.查询JSON

JMESPath是JSON的查询语言,它使您可以轻松地从JSON文档或字典中获取所需的数据。该库可用于Python,也可用于许多其他编程语言,这意味着,如果您掌握JMESPath查询语言,则可以在许多地方使用它。

以下是一些示例代码,以了解可能发生的情况:

>>> import jmespath
>>> persons = {
...   "persons": [
...     { "name": "erik", "age": 38 },
...     { "name": "john", "age": 45 },
...     { "name": "rob", "age": 14 }
...   ]
... }
>>> jmespath.search('persons[*].age', persons)
[38, 45, 14]

17.从列表或字符串中获取唯一元素

通过使用set()函数创建一个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'}

18.函数返回多个值

Python中的函数可以返回多个变量,而无需字典,列表或类。 它是这样的:

def get_user(id):
    # fetch user from database
    # ....
    return name, birthdate

name, birthdate = get_user(4)

19.*和**代表多个值的缩写

*举例如下:

>>> def f(a, b, c):
...    print(a, b, c)
...
>>> l = [1, 2, 3]
>>> f(*l)
1 2 3

**举例如下:

>>> def f(a, b):
...     print(a, b)
...
>>> args = { "a": 1, "b": 2 }
>>> f(**args)
1 2

20.检查占用多少内存

sys.getsizeof()这个函数可以检查目标占用多少内存

import sys

myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
# 87632
  • 我的微信
  • 微信扫一扫加好友
  • weinxin
  • 我的微信公众号
  • 扫描关注公众号
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: