Integer/Float calculation
Operator Description Example + Addition operator 100 + 45 = 145 - Subtraction operator 500 - 65 = 435 * Multiplication operator 25 * 4 = 100 / Float Division Operator 10 / 2 = 5.0 // Integer Division Operator 10 / 2 = 5 ** Exponentiation Operator 5 ** 3 = 125 % Remainder Operator 10 % 3 = 1
|
pi = 3.141592653 print('%10.3f' % pi)
print("pi = %.*f" % (3,pi))
print('%010.3f' % pi)
print('%-10.3f' % pi)
print('%+f' % pi)
|
List
A = [1,1,1,2,3,4,3] print(A)
|
Remove duplicates from list
int list to str list
[str(x) for x in int_list]
|
or
a_list = ["1", "2", "3"]
list(map(str, a_list))
list(map(int, a_list))
|
逐个相减
c = [b[i] - a[i] for i in range(len(a))]
|
Compare Two list
l = [1, 2, 3, 5] l_one = [2, 8, 6, 10] print set(l) & set(l_one)
|
Time
import time print(time.time()) time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
Date caculating
zhengxiangwen 2017
import datetime today = datetime.date.today() print today 2016-01-25 yesterday = today - datetime.timedelta(days=1) print yesterday 2016-01-25 tomorrow = today + datetime.timedelta(days=1) print tomorrow 2016-01-25 print "昨天:%s, 今天:%s, 明天:%s" % (yesterday, today, tomorrow)
|
For loop
for x in range(0,10): print (x,end = '')
|
Read/Write a file
f = open("demofile.txt", "r") print(f.read())
with open(fname) as f: content = f.readlines()
fo = open("foo.txt", "w") fo.write( "www.runoob.com!\nVery good site!\n")
fo.close()
with open('something.txt', 'a') as f: f.write('text to be appended')
|
print
A =" " B =u"\u2581" C =u"\u2582" D =u"\u2583" E =u"\u2584" F =u"\u2585" G =u"\u2586" H =u"\u2587" I =u"\u2588"
for i in A,B,C,D,E,F,G,H,I: print("\x1b[3;45;6m%s\x1b[0m"%(i),end='')
|
path
import pathlib pathlib.Path(__file__).parent.absolute()
import pathlib pathlib.Path().absolute()
import os sys.path[0]
import os os.chdir("../")
|
import
import XXX
from Directory import xxx
import sys sys.path.append("..") import xxx
|
str to var
for i in range(4): name='v'+str(i) locals()['v'+str(i)]=i
print v1,v2,v3
|
Dictionary
Find the max value from a dictionary
d = {'a': 10, 'b': 5, 'c': 20} max_value = max(d, key=d.get) print(max_value)
|
c