首页 > Python基础教程 >
-
Python中实用却不常见的小技巧
这是一个老外总结的Python的小技巧:
https://hackernoon.com/python-tricks-101-2836251922e0
主要来自PyTricks:
https://github.com/brennerm/PyTricks
“Talk is cheap show me the code”,这是编程人条,说半天不如几行代码更有说服力。接下来,我们就用代码说明那些不怎么常见但是非常有用的小技巧。
变量值互换

这是非常Python范儿(Pythonic)的值交互方法,省去了C、C++中的中间变量
把list的所有元素拼接成一个字符串

这个技巧其实就是使用了字符串的join()方法,连接符可以是任意字符串,被join的可以是任意的可迭代对象(iterables),比如:列表、字典、集合、元组等。
找出list中出现频率最高的元素

这里给出了两种方法,有兴趣的话,可以测试一下哪种方法更快。
判断两个字符串是否包含相同的字符

其实判断的是两个字符串中字符相同且每个字符出现的次数也相同。
反转字符串

这里有三种方法,第一种是最常见的,第三种是借用反转字符串的方法来反转整数。
反转列表

这里反转列表的方法,其实跟上面反转字符串的方法是一样的。
转置2D阵列

这里用到了内置函数zip,zip很强大,可用专门学习一下。
链式比较

这就是数学里面的数字比较,比C、C++简便
链式函数调用

(product if b else add)这个表达式返回的是函数对象,函数对象的调用
列表复制

列表的浅拷贝和深拷贝,使用的时候要注意不同场景需要不同的拷贝
字典的get方法

d.get('c', 3)就是取key为'c'的值,如果不存在该key则默认返回3
按值排序字典

给出了三种方法,都很好的方法,第一种用到了lambda函数
这样也可以的用法:for else

这个用法很少见,视情况而用。
把列表用符号拼接成字符串

这个跟之前差不多,用到了map把整数转换成字符串
合并字典

通常是update方法,前两种很少见
找出列表中最大值或最小值的index

这个方法也很少见,尤其是用到__getitem__这样的私有方法
去掉列表中重复的元素

把list转换成set再换回list,这是很经典的列表去重方法
上面这些技巧大多来自github项目PyTricks,不妨去那里看看,以学到更多的Python技巧。