python-17-tips

1.交换变量值

a, b = b, a

2.列表元素转字符串

"".join(a)

3.查找列表中频率最高的值

from collections import Counter


cnt = Counter(a)
cnt.most_common(3)

4.检查两个字符串是不是由相同字母不同顺序组成的

from collections import Counter


Counter(str1) == Counter(str2)

5.反转字符串

a[::-1]

reversed(a)

a.reverse()

6.反转列表

7.转置二维数组

list(zip(*original))

8.链式比较

9.链式函数调用

10.复制列表

deepcopy() 不影响原来的

copy() 浅拷贝实际上是引用 会改变

11.字典get方法

12.通过键排序字典元素

from operator import itemgetter


sorted(d.items(), key=itemgetter(1)

13.for else

14.转换列表为逗号分割符格式

15.合并字典

{**a, **b}

16.列表中最小和最大值的索引

def minIndex(lst):
    return min(range(len(lst)), key=lst.__getitem__)

17.移除列表中重复的元素

from collections import OrderedDict


OrderedDict.fromkeys(items).keys()