1.list prepend

# 通常都使用list的append方法,但有時候會想要從list的最前面開始append
li = [1,2,3]
a = 4
[a]+li # 方法1
li.insert(0,a) # 方法2,比方法1快好幾倍,所以直接用這個就好

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):
        # do something
        self.test()
     def func2(self):
        # do something
        self.test() 
     def test(self):
         pass

4.dictionary賦值和刪除

# 有時候想要刪除dict裡的某個key,但又不確定dict裡是否有這個key
# (1)這寫法很麻煩...,若要刪除多個不就每個都要判斷
if key in mydict:
    del mydict[key]

# (2)用try except來捕捉KeyError的狀況,但因為try except很耗資源,若刪除很頻繁不建議這樣寫
try:
    del mydict[key]
except KeyError:
    pass

# (3)這個方法完美解決上面問題,第二個參數一定要給,不過若可以確定這個key存在的話,del mydict[key] statement是效率最高的!!
mydict.pop("key", None) 

# 同理,當想要取得dict裡的值,但是不確定dict裡是否有這個key時,使用get方法
mydict.get("key", None)

5.check if a list is empty?

a = []

# (1)pythonic way
# b = {},同樣適用這個判斷式,b是空字典時boolean值是False!!!
if not a: # 因為empty list在python表示為False
  print("List is empty")
if a:
  print("List is not empty")

# (2)
if len(a):
  print("List is empty")
if not len(a):
  print("List is not empty")

# (3)最直觀的寫法
if len(a) == 0:
  print("List is empty")
if len(a) > 0:
  print("List is not empty")

## numpy array
x = numpy.array([0,1])

# pythonic way
if x:
  print("x") # 會報錯!!!!!!

# len
len( numpy.zeros((1,0)) ) # 不管array元素有多少個都只會回傳1...,所以也沒辦法用len的方式來判斷是否為空

# 正解!!!!!!!
x = numpy.array([0,1])
if x.size: print("x") # >>> x

# 測試numpy empty array
x = numpy.zeros((1,0)) # empty array
if x.size: print("x")
else: print("No x") # >>> No x

6.__name__=='__main__'

# test1.py
def addFunc(a,b):  
    return a+b  

print('test1 result:',addFunc(1,1))
# ==> test1 result: 2


# test2.py
import test1

print('test2 module result:',test1.addFunc(12,23))
# ==> test1 result: 2
# ==> test2 module result: 35
# 這狀況讓我們知道當 import module 時,也會同時執行該函數

# 為了避免這狀況
# test1.py
def addFunc(a,b):  
    return a+b  
# 當 module 是直接被執行的,會把 __name__ 變數設為'__main__',當 module 是被呼叫的 __name__ 變數會被設為 module 名稱
if __name__ == '__main__':  
    print('test1 result:',addFunc(1,1))

# 這時候執行 test2.py,就不會把 import 時候的 function 也一起執行 
# ==> test2 module result: 35

results matching ""

    No results matching ""