Python 进修笔记(一)Data type

    添加时间:2013-5-9 点击量:

    Data types:


    Sequence types: (有序的类型)



    • strings

    • tuples

    • lists


    Immutable types: (不成变的类型)



    • numbers

    • strings

    • tuples


    #String:



    text = Lists and Strings can be accessed via indices!


    String 的几种默示法:


    • Single quotes: spam
    • Double quotes: spam
    • Triple quotes: ... spam ..., ... spam ...
    • Escape sequences: s\tp\na\0m
    • Raw strings: rC:\new\test.spm



    >>> mantra = Always look
    
    ... on the bright
    ... side of life.

    >>>
    >>> mantra
    Always look\n on the bright\nside of life.

    >>> print(mantra)
    Always look
    on the bright
    side of life.


    反转字符串



    >>> S = hello
    
    >>> S[::−1]
    olleh


    str and repr: (convert number to string)



    >>> print(str(b),repr(a))
    
    b
    a
    >>> print(str(42),repr(42))
    42 42
    >>> print(str(42),repr(42))
    42 42


    character to ASCII:



    >>> ord(s
    115
    >>> chr(115
    s


    如何改变String :



    >>> S = S + SPAM!  To change a string, make a new one
    
    >>> S
    spamSPAM!

    >>> S = splot
    >>> S = S.replace(plpamal
    >>> S
    spamalot


    Format:



    >>> That is %d %s bird! % (1, dead Format expression
    
    That is 1 dead bird!
    >>> That is {0} {1} bird!.format(1, dead Format method in 2.6 and 3.0
    That is 1 dead bird!



    #List []



    L = [LondonParisStrasbourgZurich]


     The main properties of Python lists:



    • They are ordered

    • The contain arbitrary objects

    • Elements of a list can be accessed by an index

    • They are arbitrarily nestable, i.e. they can contain other lists as sublists

    • Variable size

    • They mutable, i.e. they elements of a list can be changed


      简单的copy会改变本来list的值,若是不想改变本来的值,则须要深度copy (deepcopy):



    >>> lst1 = [ab,[abba]]
    
    >>> lst2 = lst1[:]
    >>> lst2[0] = c
    >>> lst2[2][1] = d
    >>> print(lst1)
    [
    ab, [abd]]


      Deepcopy:



    >>>  copy import deepcopy
    
    >>> lst1 = [ab,[abba]]
    >>> lst2 = deepcopy(lst1)
    >>> lst2[2][1] = d
    >>> lst2[0] = c
    >>> print(lst2)
    [
    cb, [abd]]
    >>> print(lst1)
    [
    ab, [abba]]


    string to list:



    >>> S = spammy
    
    >>> L = list(S)
    >>> L
    [
    spammy]


    Operation:



    >>> s = Test List
    
    >>> l = list(s)
    >>> l
    [
    Test List]
    >>> l.append(h
    >>> l
    [
    Test Listh]
    >>> l.extend([ab])
    >>> l
    [
    Test Listhab]
    >>> l.(2,c
    >>> l
    [
    Tecst Listhab]
    >>> del l[2]
    >>> l
    [
    Test Listhab]
    >>> l.remove(t
    >>> l
    [
    Tes Listhab]

    remove all matched characters
    >>> for i in l:
    if i ==s:
    l.remove(i)


    >>> l
    [
    Te Lihab]



    >>> L = [x2 for x in range(5)]
    
    >>> L
    [0,
    1, 4, 9, 16]


    排序:



    >>> L = [abcABDaBe]
    
    >>> L.sort() Sort with mixed case
    >>> L
    [
    ABDaBeabc]
    >>> L = [abcABDaBe]
    >>> L.sort(key=str.lower) Normalize to lowercase
    >>> L
    [
    abcABDaBe]
    >>>
    >>> L = [abcABDaBe]
    >>> L.sort(key=str.lower, reverse=True) Change sort order
    >>> L
    [
    aBeABDabc]



    #Tuple ()



    tup1 = (physicschemistry, 1997, 2000);


      A tuple is an immutable list: 



    • Tuples are faster than lists.

    • If you know, that some data doesnt have to be changed, you should use tuples instead of lists, because this protect your data against accidental changes to these data.

    • Tuples can be used as keys in dictionaries, while lists cant.


      Tuple 语法:Commas and parentheses



    >>> x = (40)  An integer!
    
    >>> x
    40
    >>> y = (40,) A tuple containing an integer
    >>> y
    40,)


    Tuple to list:



    >>> T = (1, 2, 3, 4, 5
    >>> L = [x + 20 for x in T]
    >>> L
    [
    21, 22, 23, 24, 25]

    >>> T = (1, 2, 3, 2, 4, 2
    >>> T.index(2,3) 从index3开端找2
    3


    tuple immutability applies only to the top level of the ruple itself.



    >>> T = (1, [2, 3], 4
    >>> T[1] = spam This fails: cant change tuple itself
    TypeError: object doesnt support item assignment
    >>> T[1][0] = spam This works: can change mutables inside
    >>> T
    1, [spam, 3], 4)


    #Set {}



    • an unordered collection

    • unique value

    • like keys of valuesless dictionary, but supports extra operations


    Can use to remove duplicates:



    >>> L = [1, 2, 1, 3, 2, 4, 5]
    
    >>> set(L)
    {
    1, 2, 3, 4, 5}
    >>> L = list(set(L)) Remove duplicates
    >>> L
    [
    1, 2, 3, 4, 5]


    Extra operations:



    >>> engineers = {bobsueannvic}
    
    >>> managers = {tomsue}
    >>> engineers & managers
    {
    sue}
    >>> engineers | managers
    {
    anntombobvicsue}
    >>> engineers - managers
    {
    annvicbob}
    >>> managers ^ engineers Who is in one but not both?
    {anntomvicbob}



    #Dictionary {key:value}



    • Sequence operations don’t work.

    • Keys need not always be strings.

    • Assigning to new indexes adds entries.



    >>> food = {ham : yesegg : yesspam : no }



    >>> D = {spam: 2, ham: 1, eggs: 3}
    
    >>> list(D.values())
    [
    3, 1, 2]
    >>> list(D.items())
    [(
    eggs, 3), (ham, 1), (spam, 2)]


    Using dictionaries as records:



    >>> mel = {name: Mark
    jobs: [trainerwriter],
    web: www.rmi.net/˜lutz
    home: {state: COzip:80513}}
    >>> mel[jobs]
    [
    trainerwriter]
    >>> mel[jobs][1]
    writer
    >>> mel[home][zip]
    80513


    Ways to make dictionaries:



    {name: melage: 45}  Traditional literal expression
    
    D = {} Assign by keys dynamically
    D[name] = mel
    D[
    age] = 45
    dict(name
    =mel, age=45) dict keyword argument form
    dict([(namemel), (age, 45)]) dict key/value tuples form

    >>> dict.keys([ab], 0)
    {
    a: 0, b: 0}


    Turn list to dictionary:



    >>> list(zip([abc], [1, 2, 3]))  Zip together keys and values
    
    [(a, 1), (b, 2), (c, 3)]
    >>> D = dict(zip([abc], [1, 2, 3])) Make a dict zip result
    >>> D
    {
    a: 1, c: 3, b: 2}

    #new method in 3.0

    >>> D = {k: v for (k, v) in zip([a, b, c], [1, 2, 3])}
    >>> D
    {a: 1, c: 3, b: 2}




    >>> D = {c.lower(): c + ! for c in [SPAMEGGSHAM]}
    
    >>> D
    {
    eggs: EGGS!ham: HAM!spam: SPAM!}


    Sort:



    >>> D
    
    {
    a: 1, c: 3, b: 2} Better yet, sort the dict directly
    >>> for k in sorted(D): print(k, D[k]) dict iterators return keys
    ...
    a
    1
    b
    2
    c
    3



    真正的心灵世界会告诉你根本看不见的东西,这东西需要你付出思想和灵魂的劳动去获取,然后它会照亮你的生命,永远照亮你的生命。——王安忆《小说家的十三堂课》
    
    分享到: