python的骚操作
1.查找列表中出现频率最高的值
# 方法一
a = [1, 1, 2, 3, 4, 4, 4, 5, 5, 6]
max(a, key = a.count)
# 方法二
from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))
2.检查两个字符串是不是由相同字母 不同顺序组成
from collections import Counter
Counter(str1) == Counter(str2)
3.转置二维数组
list(zip(*[['a', 'b', 'a'], ['c', 'd', 'c'], ['e', 'f', 'e']]))
4.链式比较
b = 6
print(4< b < 7)
print(1 == b < 20)
5.for else
a = [1, 2, 3, 4, 5]
for i in a:
if i == 0:
break
else:
print('没有执行break')
6.合并字典
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# 方法1
{**dict1, **dict2}
# 方法2
dict(dict1.items() | dict2.items())
# 方法3
dict1.update(dict2)
7.list中的元素,两两组合
from itertools import combinations, permutations
a = [1, 2, 3]
cc = list(combinations(a, 2))
>>> [(1, 2), (1, 3), (2, 3)]
dd = list(permutations(a, 2))
>>> [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
转载自微信公众号《Python与AI社区》