跳到主要內容

Python Study (2) - Concept

 
  • Study travel beginning
       Execute your first code Hollow World
        >>> print("Hollow World")
         Hollow World


    Python's core Data Type
           We understand  data type before studying any program. Python has built-in object types


    Data Type(Object type) Example
    Numbers int, float, long, complex
    Strings  
    Lists  
    Dictionaries  
    Tuples  
    Files  
    Sets set, frozenset
    Primitive types boolean,
    Program unit types Functions, modules, classes
    Implementation-related types compiled code, stack tracebacks


    1. Number
        Example: real number, float, double ...
    >>> 333 + 555
        888
    >>> 333 / 111
       3.0
    >>> 333 * 9
       2997
    >>> "happy " * 2 + " birthday"
       'happy happy  birthday'

    Module : math and random
    >>> import math
    >>> math.pi
    3.141592653589793
    >>> import random
    >>> random.random()
    0.7082048489415967
    >>> random.choice([2,4,6,8])
    4
    Note : intelligent complement => tab

     

    2. String
    (1) String is a array of char

    >>> S = 'Money'
    >>> S[0]
    'M'
    >>> S[-1]
    'y'
    >>> S[0:-1]
    'Mone'
    >>> len(S)
    5
    >>> S[:]
    'Money'
    >>> S[1:]
    'oney'
    >>> S[:3]
    'Mon'

    (2) Unicode String
    https://docs.python.org/2/howto/unicode.html.
    Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed.Python’s strings also come with full Unicode support  required for processing text in internationalized character sets.
     
    Python 2.X  
         In python 2.X, All Strings represent a collection of bytes, Python is default ASCII
         script. If you want change non-ASCII script for the script, you need put first line
         to declare encoding declaration.
       
         * Use Python Script edit the code and run . Ref: Use IDLE
          
         The length of the string is not 2 but rather 4, because each chinese word
         contain 2 bytes. len() function return length of bytes
       

    # coding=big5
    text = "哈囉"   #The word is a Chinese word than meas "hello"
    print len(text)

    4  # the result after run


        What does it happen when use encoding declaration. The result return 2 length
        of the string.

    # coding=big5   #encoding declaration
    text = u"哈囉"      #python 2.x use “u” to represent Unicode
    print len(text)

    2  # the result after run

     
         Note:  Python 2.x need to declarate encoding declaration.
         Both 3.X and 2.X use  “\x” hexadecimal  and  “\u” to represent Unicode

    >>> text = u’哈囉’
    >>> text
    u'\xab\xa2\xc5o'

     


    Python 3.x        
        Python 3.x all strings are unicode encode.

    text = "哈囉"   #The word is a Chinese word than meas "hello"
    print(len(text))

    4  # the result after run
              

    Encode and decode

    function description example
    unichr(int ) return unicode

    >>> unichr(80)
    u'P'

    chr(int ) return integer

    >>> chr(80)
    'P'

    ord(str ) return ASCII or Unicode

    >>> ord(u'A')
    65

    encode(str) return encode string >>>
    decode(str) return decode string  
    unicode return unicode string  

    (3) Pattern Matching
    Module : re


    >>>import re
              

    3. Lists
    Lists are ordered arbitrary collection of objects and they have no fixed size.they are sequence objetcs

    >>> L = ["toast", 10, "toast with egg", 12.5, "toast with ham", 15]
    >>> len(L)
    6

    >>> L[0:2]
    ['toast', 10]

    >>>L[:-1]
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham']

    >>>L + ["toast with vegetable", 20]
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15, 'toast with vegetable', 20]
              
    List functions
    function description example
    append add object at end of list >>> L.append(“toast with vegetable”)
    >>> L
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15, 'toast with vegetable']
    pop get object and remove >>> L.pop(-1)
    >>> L
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15]
    sort sort

    >>> M = ["Banana","Apple","Orange"]
    >>> M.sort()
    >>> M
    ['Apple', 'Banana', 'Orange']

    reverse  

    >>> M.reverse()
    >>> M
    ['Orange', 'Banana', 'Apple']

    keys return keys of the list  
    values return values of the list  

    List Arrary

    >>> L= [ [ 'toast','toast with egg','toast with ham','toast with vegetable'],
             [10,12.5,15,20]]
    >>> L[0]
    ['toast', 'toast with egg', 'toast with ham', 'toast with vegetable']

    >>> [row[1] for row in L]
    ['toast with egg', 12.5]
              
    range(int) : A built-in function is used to generate integers

    >>>List(range(5))
    [0,1,2,3,4]

    >>>for i in range(4):
                print(i)

    0
    1
    3
    4

    >>> list(range(1,4))
    [1,2,3]

    >>> list(range(1,8,2))
    [1, 3, 5, 7]
              
    map(function, iterable, ...) : map is a build-in function. Apply function to every item of iterable and return a list of the results.


    >>>List(range(5))

    >>> list1 = [1,2,3]
    >>> list2 = [1,2,3]
    >>> def sum(a,b):
        return a+b

    >>> list(map(sum, list1, list2))  #python 3.x use a list to store map 
    [2, 4, 6]
    >>>

              

    Dictionaries
    (1) kye/value
    (2) sequence


    >>> food = {"toast": 10, "toast with egg": 13.5, "toast with ham":15}
    >>> food["toast with egg"]
    13.5

    >>> food["toast with egg"]+=1
    >>> food["toast with egg"]
    14.5

    >>> food["toast with vegetable"] = 20
    >>> food["toast with vegetable"]
    20

              
    Dictionaries function

    dict : It is a name=value format and make dictionaries

    >>> newfood = dict(toast=15, toast_with_egg=20, toast_with_ham=25)}>>> newfood[toast_with_egg]
    Traceback (most recent call last):
      File "<pyshell#19>", line 1, in <module>
        newfood[toast_with_egg]
    NameError: name 'toast_with_egg' is not defined


    >>> newfood["toast_with_egg"]
    20

              

    zip :
    function :  zip([key1, key2, key3….], [value1, value2, value3…])

    >>>  dict(zip(['toast','toast with egg','toast with ham'],[10,12.5,15]))
    >>> newfood2["toast"]
    10

              
    build-in function

    >>> food= [ [ 'toast','toast with egg','toast with ham','toast with vegetable'],
             [10,12.5,15,20]]

            
    function description example
    keys show keys of the list

    >>> food.keys()
    ['toast', 'toast with ham', 'toast with vegetable', 'toast with egg']

    sort sort value of the list

    >>> foodMoney = list(food.values())
    >>> foodMoney.sort()
    >>> foodMoney
    [10, 14.5, 15, 20]

    values get values of the list

    >>> foodMoney = list(food.values())
    >>> foodMoney
    [10, 15, 20, 14.5]

    reverse  

    >>> foodMoney = list(food.values())
    >>> foodMoney.reverse()
    >>> foodMoney
    [20, 15, 14.5, 10]

       


    Tuples
    (1) sequence
    (2) fixed size
    (3) immutable (when the tuple is created, it connot be changed)

    >>> fruit = ("apple","organe","grape","banana")
    >>> fruit
    ('apple', 'organe', 'grape', 'banana')

    >>> fruit[0]
    'apple'

              
    built-in function

    >>> fruit = ("apple","organe","grape","banana")
    >>> fruit
    ('apple', 'organe', 'grape', 'banana')

    >>> fruit[0] = "tomato"
    Traceback (most recent call last):
      File "<pyshell#86>", line 1, in <module>
        fruit[0] = "tomato"
    TypeError: 'tuple' object does not support item assignment

              
    function description example
    index(object) return index of the tuple

    >>> fruit.index("banana")
    3

    count(object) return times of appear object in the tuple

    >>> fruit.count("apple")
    1









     

  • 留言

    這個網誌中的熱門文章

    JavaBean 和POJO

    前言 今天介紹JavaBean和POJO的不同,這兩個名詞在JAVA文章常常被拿來使用以及討論。在JDK1.1時候釋出才有的一個標準架構,很多時候常常被搞混,所以我們特別開闢一章來加以討論。POJO規範在企業級應用已經廣大的被使用的規範。 解釋 POJO : 全名為Plain-old-Java-object,只需要繼承Object就可以,沒有特定規定,只要建立的類別有setter/getter方法都可以稱為POJO JavaBean: JavaBean通常用來封裝多個物件成為單獨物件使用,規範比較嚴格,規則如下 規則 說明 1 需要實作序列(Serializable/Externalizable) 2 不能有參數的建構子( no-arg constructor) 3 需要有公用setter/getter 4 屬性必須要私人(private) 5 屬於特定POJO規則 比較 所有的JavaBean都為POJO,但是所有的POJO不一定為JavaBean 都可以當作重複元件 都必須序列化 特性都為可用性、易用性和持久化使用 - 應用 由圖我們可以知道POJO在應用程式中,主要用來存取資料庫資料達到持久化的目的,並提供給商業邏輯流程處理使用。這種POJO的架構提供程式人員開發時的可以很有規則將資料封裝並加以使用。 範例1. JavaBean(以員工為實例) JavaBean建立員工物件,可以發現Employee物件建構子沒有任何參數,屬性為私有化並setter/getter的命名方式。 //實作序列化 public class Employee implements java.io.Serializable{ private int id; private String name; //無參數建構子 public Employee(){} //以下實作setter/getter public void setId(int id){this.id=id;} public int getId(){return id;} public void setName(String ...

    Python AI-問題集

    Python AI-問題集 問題集 Jupyter Notebook執行ipywidgets會出現kernel死掉的錯誤發生(The kernel appears to have died) 解決方法 (1) 根據log檔來判斷問題: 例如:log訊息出現OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized. (2) 根據問題關鍵字找出問題所在: 利用google查詢所遭遇到的問題,例如我把上面的問題上google查詢可以找到這篇的解法 https://blog.csdn.net/bingjianIT/article/details/86182096 (3)實作解法: 我實作下面解法後,就可以順利執行手寫辨識的程式. //在Python宣告時加入 import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" 參考 https://blog.csdn.net/bingjianIT/article/details/86182096

    GSON 進階教學

    GSON進階教學 完成 基礎教學 後,本章節教你如何處理在非正常情況下,如何完成反序列與序列動作。 泛型轉換 序列化與反序列化時,客製化輸入出JOSN字串@SerializedName 忽略物件屬性輸出@Expose 泛型轉換 泛型做Json序列/反序列時,比較麻煩地方是泛型在運行期間相關的參數就會被抹除所以無法知道原來的類別。我們建立一個播放器(Play)類別,它為泛型的類型,它可撥放MP3、CD等等,所以建立一個CD媒介(CD)類別。Play使用類型為泛型T, 物件 屬性 播放器 Play 類型 type CD媒介 CD 歌 songs /**' * 播放器 * @param */ public class Play { T type ; public Play(T t){ this.type = t; } @Override public String toString() { return this.type.toString(); } } /** * CD 音樂物件 */ public class CD { private List songs ; public CD(String ...songs){ this.songs = new ArrayList() ; for(String song : songs){ this.songs.add(song) ; } } @Override public String toString() { StringBuilder sb = new StringBuilder() ; sb.append(""); for(String s:songs){ sb.append(""+s+",\r\n"); } sb.append("")...