Python || 基礎用法 - SeanWu1977/Machine-Learning GitHub Wiki

補0

'{:0>2}'.format(5) 左邊  -> 05
'{:0<2}'.format(5) 右邊  -> 50

快速寫法

b'afdasf' == 'afdasf'.encode('ascii')

快速寫法

* 如a為False or None,則c = 10( 同 if a then a else 10), 用於指定初始值(function輸入參數預設為None or False)
c = a or 10

* format 新寫法 f-string
'5*3={}'.format(5*3)
f'5*3={5*3}'  #速度較format快 (python 3.6以上支援)

width = 10
precision = 4
value = decimal.Decimal("12.34567")
f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

'{:%Y-%m-%d %H:%M:%S.%f}'.format(datetime.now())
f'{datetime.now():%Y-%m-%d %H:%M:%S.%f}'
參閱  [1] https://wxnacy.com/2018/01/03/python-format/
     [2] https://pyformat.info/
     [3] https://www.python.org/dev/peps/pep-0498/

check variable exist

* check local variable:
if 'Var' in locals():
  # Var exists.

* check global variable:
if Var' in globals():
  # Var exists.

* an object has an attribute:
if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.
if hasattr(self, 'attr_name'):

物件@property and setattr

class test1():
    def __init__(self):
        self._foo = None  # 會直接call __setattr__ 

    @property
    def foo(self):   # foo為固定名稱,實際是存_foo
        return self._foo   

    @foo.setter      # foo為之前設定的名稱,不可改
    def foo(self,value):  # foo為之前設定的名稱,不可改
        print("org foo {}".format(self._foo))
        self._foo = value
        print("new foo {}".format(self._foo))

    def __getattribute__(self,name): #不管訪問的屬性存不存在都會被執行()
        ...

    def __setattr__(self,name, value): #注意有用@property時,要用super().__setattr__(name, value)才能呼叫到
        if name != 'foo':
            self.__dict__[name] = value
            print("self.{} = {}".format(name,value))
        else:
            super().__setattr__(name, value)
 
    def __getattr__(self,name): #在訪問的屬性不存在时才會被執行(),會在__getattribute__後執行
        print("no value")

class 中,變數前加__即為私有變數,外部不能呼叫

class test1():
    def __init__(self):
        self.__foo = 'a'

a = test1()
print(a.__foo)  # 會有AttributeError: 'test1' object has no attribute '__foo'
print(a._test1__foo) # 就可以破解了,但一般不會去用這種方式存取(開發者有一定目的才會使用__)

傳回 list 中,大於10的項目。(回傳為一list, 因為[ ] 在外層。)

[x for x in <list> if x > 10]

raw string

r'<string>'

unicode string

u'<string>'

zip用法

zip(x,y)
x = [1,2,3,4]
y = [5,6,7,8]
zip(x,y) = [(1,5),(2,6),(3,7),(4,8)]

map用法

map(object.method, objectlist)
#objectlist內每一個object執行method
list(map(object.method, objectlist))
#objectlist內每一個object執行method後,顯示回傳值

python 內積 (2,3較好)

  1. sum([x*y for i,j in zip(x,y)])
  2. x.dot(y) (import numpy as np)
  3. np.dot(x,y) (import numpy as np)

Conditional expressions

[ function(x) if x > 0 else '' for x in row ]
對每一筆row,當x > 0 執行function(x) 否則 回傳 ''
輸入長度 = 輸出長度

list comprehensions

[x for x in S if x % 2 == 0]
對每一個 x 而言, 只有x % 2 == 0 時回傳x至list
輸入長度 >= 輸出長度

關於class變數

新instance之變數再還沒操作時,會參照class的預設值。
此時class的值變動,instance之變數就會變動。

當instance對該變數進行變動時,該變數才會與class的值脫離。
此時class變數怎麼改,instance變數都不會影響

用法:可對所有該class的instance同時變動該變數的值,達到統一值。

self.var 指的是instance變數

dictionary

for key in dict: # key 是key值
for key, value in dict.items(): # key 是key值, value是值

function(**kwargs)<BR>
# 呼叫時 function(a=123, b=444)
kwargs = {'a':123,'b':444}

# 參數預設值用法:
option= {'prot': 21, 'ip': '10.0.1.2', 'uaer': 'sean'}  # 此為預設值
# 呼叫  
function(port=123, pwd=444)
# 此時  kwargs = {'prot': 123, 'pwd': 444}
option.update(kwargs) #用此方法即可更新option的值
# 注意pwd原本並不存在,但update後,會產生此key,value
option 此時為 {'prot': 123, 'ip': '10.0.11.2', 'uaer': 'sean',** 'pwd': 444**}

def fun(arg1,arg2,arg3='three'):

args1 = (1,3,4)
fun(*args1)
# 則 arg1 =1, arg2=2, arg3=3
option= {'arg1': 21, 'arg2': '10.0.1.2'}
fun(**option)
 # 則 arg1 =21, arg2='10.0.1.2', arg3='three'

dict get 用法

name_for_userid = {
    382: "Alice",
    590: "Bob",
    951: "Dilbert",
}

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")
# 沒找到key回傳的value為"there"
⚠️ **GitHub.com Fallback** ⚠️