欧2020

导航

python学习记录(四)-意想不到

计数

from collections import Counter
# 计数
res = Counter(['a','b','a','c','a','b'])
print(res,type(res)) 
# Counter({'a': 3, 'b': 2, 'c': 1}) <class 'collections.Counter'>
print(dict(res)) # {'a': 3, 'b': 2, 'c': 1}
# 按次数创建容器
res = Counter(a=3,b=2,c=0)
print(list(res.elements())) # ['a', 'a', 'a', 'b', 'b']
# 最常见排序
res = Counter('abcefcaabf').most_common(3)
print(res,type(res)) # [('a', 3), ('b', 2), ('c', 2)] <class 'list'>

数组中排成最小数(cmp_to_key)

# [3,30,34,59] ==> 3033459
def fun_rules(x,y):
    a,b = x + y,y + x
    if a>b:
        return 1
    elif a<b:
        return -1
    else:
        return 0

import functools
varlist = [3,30,34,59]
varlist = [str(i) for i in varlist]
varlist.sort(key=functools.cmp_to_key(fun_rules))
res = ''.join(varlist)
print(res) # 3033459

数组中排成最小数(全排序)

varlist = [3,30,34,59]
from itertools import permutations
res = list(permutations(varlist))
print(res)
varnew = []
for i in res:
    temp = [str(x) for x in i]
    varnew.append(''.join(temp))
print(varnew)
varnew.sort()
print(varnew[0]) # 3033459

全排列

from itertools import permutations
# 不指定长度
varlist = [1,2,3]
res = permutations(varlist)
print(list(res)) # [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
# 指定长度
res = permutations(varlist,r=2)
print(list(res)) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

迪卡尔集

from itertools import product
list1 = ['a','b']
list2 = [1,2]
res = product(list1,list2,repeat=1)
print(list(res)) # [('a', 1), ('a', 2), ('b', 1), ('b', 2)]

排列组合排序

# 不重复
from itertools import combinations
varlist = [2,1,3,4]
res = combinations(varlist,r=2)
print(list(res)) # [(2, 1), (2, 3), (2, 4), (1, 3), (1, 4), (3, 4)]
# 可重复
from itertools import combinations_with_replacement
res = combinations_with_replacement(varlist,r=2)
print(list(res)) # [(2, 2), (2, 1), (2, 3), (2, 4), (1, 1), (1, 3), (1, 4), (3, 3), (3, 4), (4, 4)]

截止到当前位置求和/取最大值

from itertools import accumulate
nums = [1, 3, 2, 4]
print(list(accumulate(nums))) # [1, 4, 6, 10]
print(list(accumulate(nums,max))) # [1, 3, 3, 4]

2个容器取对应值

from itertools import compress
nums1 = ['a','b','c','d']
nums2 = [1, 0, 1, 0]
print(list(compress(nums1, nums2))) # ['a', 'c']

posted on 2020-12-17 18:29  欧2020  阅读(51)  评论(0编辑  收藏  举报