pylist

Python 库函数背诵树

Sequence (list, tuple)

Data management: non-slicing style

Data management: slicing Style

数学运算

Set

数学运算

Data management

Dict

Data management

关于方向

Operations with defaults

deque

from collections import deque

heapq

from heapq import heapify, heappush, heappop
h = ***
heapify(h)
heappush(h, x)
x = heappop(h)
print(h[0]) # peek

max heap 的 负号位置

h = [-x for x in array]
heapify(h)
heappush(h, -x)
x = -heappop(h)
print(-h[0]) # peek

常用技巧

用for-else代替flag的使用

for item in container:
    if search_something(item):
        # Found it!
        process(item)
        break
else:
    # Didn't find anything..
    not_found_in_container()

Lambda function

fun1 = lambda x: -x * 10
print(fun1(1))
-10

same as

def fun2(x): return -x * 10
print(fun2(1))
-10

in sorting

a = [1, 4, -1, -3]
print(sorted(a))
print(sorted(a, key=fun1))
print(a)
print(a.sort(key=fun2))
print(a)
[-3, -1, 1, 4]
[4, 1, -1, -3]
[1, 4, -1, -3]
None
[4, 1, -1, -3]

a.sort() won’t return anything

ab = {'a':1, 'b':2, 'c': 4, 'd':3}
data = 'babdc'
data.sort()
      1 ab = {'a':1, 'b':2, 'c': 4, 'd':3}
      2 data = 'babdc'
----> 3 data.sort()

AttributeError: 'str' object has no attribute 'sort'
print(sorted(data))
print(sorted(data, key=lambda x: ab[x]))
['a', 'b', 'b', 'c', 'd']
['a', 'b', 'b', 'd', 'c']

Sort table

List 是可以按元素直接比较的,左边的权重高。 所以List of List 是可以直接sort的。 也可以取最值。 也可以heap。

详情

Example

key in heap

heappush() and heappop does not have key attr. Need to define a __lt__() function for the same propose

from heapq import heappush, heappop
# self defined value
ab = {'a':1, 'b':2, 'c': 4, 'd':3}
# data
data = 'babdc'
# char class to define the comparison function
class char:
    def __init__(self, val):
        self.val = val
    def __lt__(self, other):
        if ab[self.val] < ab[other.val]:
            return True
        else:
            return False
# heap sort
h = []
for c in data:
    heappush(h, char(c))
ans = []
while h:
    ans.append(heappop(h).val)
print(ans)
['a', 'b', 'b', 'd', 'c']

Zip

zip 的操作是把同index放在一个tuple里,所以和转置息息相关。 注意zip的输出不是list,而是一个zip,可用作iter

使用zip函数转置list of tuples

# initializing list of tuples 
test_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)] 
  
# Printing original list 
print ("Original list is : " + str(test_list)) 

# perform Unzipping 
res = list(zip(*test_list)) 
      
# Printing modified list  
print ("Modified list is : " + str(res)) 
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]

注意事项