dreamlike-zzg

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 排序

s = 'aaabbc'
set(s)
# {'a', 'b', 'c'}
sorted((s.count(x), x) for x in set(s))
# [(1, 'c'), (2, 'b'), (3, 'a')]

# 排序后索引
>>> lis = [1,2,3,0,1,9,8]
>>> sorted(range(len(lis)), key=lambda k: lis[k])
[3, 0, 4, 1, 2, 6, 5]

deque 

import collections
deque = collections.deque([1,2,3])
deque.append(4)
a = deque.popleft()

heap

# 若item为list或tuple,依次比较item中的每个元素
import heapq
heap = []            # creates an empty heap
heapq.heappush(heap, item) # pushes a new item on the heap
item = heapq.heappop(heap) # pops the smallest item from the heap
item = heap[0]       # smallest item on the heap without popping it
heapq.heapify(heap)           # transforms list into a heap, in-place, in linear time
item = heapq.heapreplace(heap, item) # pops and returns smallest item, and adds
                               # new item; the heap size is unchanged
_heappop_max(heap)
_heapreplace_max(heap, item)
_heapify_max(x)

ascii

chr(97)  # 'a'
ord('a') # 97

二进制

# https://www.cnblogs.com/renke123/p/11029906.html
int('0b1010',2) 
int('1010',2) # 10  
bin(10) # '0b1010'

当前路径

import os, sys
sys.path # list, python环境路径,import路径,自动加入当前.py所在的文件夹路径(第一个元素)
os.getcwd() # 运行命令时的cd路径

静态方法:无法访问类属性、实例属性,相当于一个相对独立的方法,跟类其实没什么关系,换个角度来讲,其实就是放在一个类的作用域里的函数而已。

类成员方法:可以访问类属性,无法访问实例属性。上述的变量val1,在类里是类变量,在实例中又是实例变量,所以容易混淆。

class MyClass:
    val1 = 'Value 1'
    def __init__(self):
        self.val2 = 'Value 2'

    @staticmethod
    def staticmd():
        print '静态方法,无法访问val1和val2'

    @classmethod
    def classmd(cls):
        print '类方法,类:' + str(cls) + ',val1:' + cls.val1 + ',无法访问val2的值'

global、nonlocal

num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num) 
    num = 123
    print(num)
fun1()
print(num)

out:
1
123
123

def fun():
    num = 1
    def outer():
        num = 10
        def inner():
            nonlocal num   # nonlocal关键字声明
            num = 100
            print(num)

        inner()
        print(num)

    outer()
    print(num)
fun()

out:
100
100
1

 自定义排序

a = [1,2,4,3,5]
def compare_personal(x,y):
    pass
a.sort(key= functools.cmp_to_key(compare_personal))
c = sorted(b, key=functools.cmp_to_key(compare_personal))

 

posted on 2022-11-05 15:59  梦幻济公  阅读(20)  评论(0编辑  收藏  举报