1、查找列表中频率最高的值
from collections import Counter
a = [1,2,3,1,2,3,1,2,2,2,4,5,7]
print(max(set(a), key=a.count))
cnt = Counter(a)
print(cnt.most_common(4)) #计算每个元素出现频率 4代表前面四个元素
2、检查两个字符串是不是由相同的字母不同顺序组成
str1 = 'li chao'
str2 = 'chao li'
print(Counter(str1) == Counter(str2))
3、反转字符串
for char in reversed(str1):
print(char)
b = 12345678
print(int(str(b)[::-1]))
4、转置二维数组
original = [['a', 'b'],['c', 'd'], ['e', 'f']]
transposed = zip(*original)
print(list(transposed))
5、链式函数调用
def product(a, b):
return a * b
def add(a, b):
return a + b
b = False
print((product if b else add)(5,7))
5、通过键对字典元素排序
m = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1}
print(sorted(m.items(), key=lambda x: x[1]))
from operator import itemgetter
print(sorted(m.items(), key=itemgetter(0)))
print(sorted(m, key=m.get))
6、转换列表为逗号分隔符格式
也就是列表类型转换为字符串
list = ['foo', 'bar', 'xyz']
print(','.join(list))
numbers = [2, 4, 5, 10]
print(','.join(map(str,numbers)))
data = [2, 'hello', 3, 3.4]
print(','.join(map(str, data)))
7、合并字典
d1 = {'a': 1}
d2 = {'b': 2}
print({**d1, **d2})
print(dict(d1.items() | d2.items()))
d1.update(d2)
print(d1)
8、列表中最大和最小值索引
list1 = [40, 10, 20,30]
def minIndex(list1):
return min(range(len(list1)), key=list1.getitem)
def maxIndex(list1):
return max(range(len(list1)), key=list1.getitem)
print(minIndex(list1))
print(maxIndex(list1))
9、移除列表中重复的元素
list2 = [2,2,3,3,1]
newlist2 = list(set(list2))
print(newlist2)
from collections import OrderedDict
list3 = ['foo', 'bar', 'bar', 'foo']
print(list(OrderedDict.fromkeys(list3).keys()))
网友评论