1.list prepend
li = [1,2,3]
a = 4
[a]+li
li.insert(0,a)
2.datetime object convert to timestamp
import time
from datetime import datetime
print(time.mktime(datetime.now().timetuple()))
>>> 1519203467.0
3.類別裡的函數如何互相調用?
class MyClass:
def __init__(self):
pass
def func1(self):
self.test()
def func2(self):
self.test()
def test(self):
pass
4.dictionary賦值和刪除
if key in mydict:
del mydict[key]
try:
del mydict[key]
except KeyError:
pass
mydict.pop("key", None)
mydict.get("key", None)
5.check if a list is empty?
a = []
if not a:
print("List is empty")
if a:
print("List is not empty")
if len(a):
print("List is empty")
if not len(a):
print("List is not empty")
if len(a) == 0:
print("List is empty")
if len(a) > 0:
print("List is not empty")
x = numpy.array([0,1])
if x:
print("x")
len( numpy.zeros((1,0)) )
x = numpy.array([0,1])
if x.size: print("x")
x = numpy.zeros((1,0))
if x.size: print("x")
else: print("No x")
6.__name__=='__main__'
def addFunc(a,b):
return a+b
print('test1 result:',addFunc(1,1))
import test1
print('test2 module result:',test1.addFunc(12,23))
def addFunc(a,b):
return a+b
if __name__ == '__main__':
print('test1 result:',addFunc(1,1))