-
Notifications
You must be signed in to change notification settings - Fork 0
/
Python_utils.txt
74 lines (74 loc) · 2 KB
/
Python_utils.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
1) List
lst1 + lst2
cmp(list1, list2)
sorted(lst)
lst.sort()
lst.append(e)
lst.pop([i]) # i is optional; cannot pop from an empty list
lst.extend(L) # equals to a[len(a):] = L
lst.insert(i,e) # check what the result is when abs(i) > e
lst.index(e) # find the first appearance of e
lst.count(e)
lst.remove(e) # remove the first appearance of e
del lst[i]
del lst[i:j]
del lst[:]
2) String
# See: https://docs.python.org/2/library/stdtypes.html#string-methods
print r'C:\some\name' # use raw string
print 'hi\
yourself'
a = 'Py' 'thon'
s='a' s[1:] # out of range slice indexes are handled gracefully
''.join(['h','i'])
''.join(str(x) for x in lst)
'1 2'.split() # default to split on space
'abc'[::-1] # reverse a string
'abcde'[3:0:-1] # 'dcb', s[start:end:step]
list('abc')
for c1, c2 in zip(s1,s2)
from string import printable
s.encode('hex')
"%x" % 123
3)
4) if __name__ == '__main__':
5) bitwise operators: x<<y, x>>y, x&y, x|y, ~x, x^y
6) for i in range(len(lst)-1,-1,-1):
7) {char:[] for char in Set}
8) min(lst, key=foo); min(string_1, string2, len)
9) min(result_l,result_r,key=lambda x:x[0])
10) lst = [[k,v] for k,v in dic.items()]
11) lst = filter(lambda item: item != '', lst)
12) lst = map(lambda x:int(x),lst)
value = reduce(lambda x, y : x + y, [1,2,3])
13) int('5f',16)
14) import re
pattern = re.compile(r'\s+')
string = re.sub(pattern, '', string)
re.match(pattern, string)
15) import sys
try:
txt = open(sys.argv[1],"rt")
line = txt.readline()
except:
print "File does not exist!"
sys.exit()
16) import string
digs = string.digits + string.letters
17) from collections import deque
queue = deque([1,2,3])
queue.append(4)
queue.popleft() # FIFO
from collections import Counter
a=Counter('aabc')
from collections import defaultdict
dic = defaultdict(int)
18) integer division: a // b
19) from fractions import Fraction
a=Fraction(*[1,2])
a.denominator
a.numerator
20) eval("x + 3")
21) any(lst)
all(lst)
22) import unittest