python基礎データ構造--リスト(list)、元祖(tuple)、辞書(dict)、文字列(string)、集合(set)紹介と相互変換

8934 ワード

pythonは便利なデータ処理ツールで、検索を行う多くの言語で使われています.簡単で使いやすく、機能が強いのがメリットです.複雑な機能は数行のコードでしかできません.
迅速な開発で、性能の安定性に対する要求は高くなく、それを使うのに最適です.
まず系統的な学習の下で.
一)内容紹介
pythonの基礎データ構造は、リスト(list)、元祖(tuple)、辞書(dict)、文字列(string)、集合(set)である.
1)リスト(list)
主な方法:
  • List
  • を作成する
    >>> l = [1,(1,2),2,"3"]
    >>> print l
    [1, (1, 2), 2, '3']
  • 追加
  • list.append(x)#リストに要素を追加し、list[len(list):]=[x]に等しい
    list.extend(L)#リストにリストを追加します.リスト[len(list):]=Lに等しいです.
    list.insert(i,x)#指定された位置に要素xを挿入
    >>> l = [1,(1,2),2,"3"]
    >>> print l
    [1, (1, 2), 2, '3']
    >>> l.append(5)
    >>> print l
    [1, (1, 2), 2, '3', 5]
    >>> l.extend([])
    >>> print l
    [1, (1, 2), 2, '3', 5]
    >>> l.extend([6])
    >>> print l
    [1, (1, 2), 2, '3', 5, 6]
  • 更新
  • 適切な関数がない場合は、下付きラベルを使用して値を取り、値を割り当てることができます.例えば、l[1]=1.5
    >>> l = [1, (1, 2), 2, '3', 5, 6]
    >>> l[1] = 1.5
    >>> l
    [1, 1.5, 2, '3', 5, 6]
  • 削除
  • list.remove(x)#最初のx要素を削除し、要素xがなければ、エラーを報告します.
    list.pop([i])#位置決めiにリストを削除し、iがなければリストの最後の要素を削除
    List[i:j]#は、補間に使用できる参照値の部分を説明する
    >>> l
    [1, 1.5, 2, '3', 5, 6]
    >>> l.append(1)
    >>> l.append(1)
    >>> l.remove(1)
    >>> l
    [1.5, 2, '3', 5, 6, 1, 1]
    >>> l.remove(10)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: list.remove(x): x not in list
    >>> l.pop()
    1
    >>> l
    [1.5, 2, '3', 5, 6, 1]
    >>> l.pop(0)
    1.5
    >>> l
    [2, '3', 5, 6, 1]
    <pre code_snippet_id="193616" snippet_file_name="blog_20140218_1_3845041" class="python" name="code">>>> list[0:0] = ['sample value']
    >>> print list
    ['sample value', '2', '3']
    >>> list[0:0] = ['sample value', 'sample value 1']
    >>> print list
    ['sample value', 'sample value 1', 'sample value', '2', '3']
    >>> list[1:2] = ['sample value 2', 'sample value 3']
    >>> print list
    ['sample value', 'sample value 2', 'sample value 3', 'sample value', '2', '3']
     
       
       
      
    • 取值
    list.index(x) # 取第一个为x的元素位置,如果没有报错

    list[i] #取i位置的元素

    list[i:j] #取>=i&& < j的列表片段, 如果i或者j为空,则表示取开始到j的片段列表或者i到结尾的列表片段。 如果j=-1,表示i到倒数第一个元素的列表片段(相当于j = len(list) -1)。

    >>> l
    [2, '3', 5, 6, 1]
    >>> l.append(2)
    >>> l.index(2)
    0
    >>> l.index(7)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: 7 is not in list
  • 計算個数
  • list.count(x)#統計xリスト内の個数、0なし
    >>> l
    [2, '3', 5, 6, 1, 2]
    >>> l.count(2)
    2
    >>> l.count(10)
    0
  • ソート
  • list.sort(cmp=None,key=None,reverse=false)#ソート
  • 逆順
  • list.reverse()#逆シーケンス
    >>> l
    [2, '3', 5, 6, 1, 2]
    >>> l.sort()
    >>> l
    [1, 2, 2, 5, 6, '3']
    >>> l.reverse()
    >>> l
    ['3', 6, 5, 2, 2, 1]
    
    

    2)タプル(tuple)
    #メタグループとリストは非常に似ていますが、メタグループと文字列は同じです.
    可変ではありません.つまり、メタグループを変更できません.
    tuple = ('a', 'b', 'c', 'd', 'e')
    >>> print tuple[0]
    a
    >>> print tuple[0:2]
    ('a', 'b')

    3)文字列(string)
    string = "Hello My friend"
    >>> print string[0]
    H
    >>> print string[0:5]
    Hello
    
              :in,not in
    >>> print 'He' in string
    True
    >>> print 'sHe' in string
    False
    
    *               ,   
    print 'hello'*5
    >>> hellohellohellohellohello 
    
    string  ,        , 
    S.find(substring, [start [,end]]) #        ,     ,    -1
    S.rfind(substring,[start [,end]]) #    
    S.index(substring,[start [,end]]) # find,       ValueError  
    S.rindex(substring,[start [,end]])#      
    S.count(substring,[start [,end]]) #         
    
    S.lowercase()
    S.capitalize()      #     
    S.lower()           #   
    S.upper()           #   
    S.swapcase()        #     
    
    S.split(str, ' ')   # string list,     
    S.join(list, ' ')   # list string,     
    
              
    len(str)                #   
    cmp("my friend", str)   #     。    ,  1
    max('abcxyz')           #           
    min('abcxyz')           #           
    
    string   
                
    float(str) #     ,float("1e-1")     0.1
    int(str)        #    ,  int("12")     12
    int(str,base)   #  base     ,int("11",2)    2
    long(str)       #     ,
    long(str,base)  #  base     ,
    
           (       ,   C   , )
    str_format % (    ) #      tuple      ,        
    >>>print ""%s's height is %dcm" % ("My brother", 180)
    #      My brother's height is 180cm

    4)辞書(dict)
    key-valueのデータ構造は、c++のstl:mapと似ています.
    #    :
    #1)  
    d = {} #   
    d = {'name':'tom', 'age':22}
       #  
    d = {}
    d['name'] = 'tom'
    d['age'] = 22
    2)dict
    d = dict() # 
    d = dict(name='tom', age=22)
    
    d = dict([('name','tom'), ('age',22)])
      #  
    keys = ['name','age']
    values = ['tom', 22]
    d = dict(zip(keys,values))
    
    #3) fromkeys
    >>> dict.fromkeys(['name','age'],'default_value')
    {'age': 'default_value', 'name': 'default_value'}
    
    #  key    
    if k in d:   #k not in
        dosomething()
    
    #  
    print d['name'] #      ,       ,     KeyError。  ,     
    print d.get('name', 'jack') #    ,     ,       default_value.     default_value  None
    
      #    
    if k in d:
        print d[k]
    
    try:
        print d[k]
    except KeyError:
        dosomething()
    
    print d.get(k, default)
    #   d[k] if k in d else default
    
    
    #  
    for key in d:
        print key, d[key]
        #   for key in d.keys()
    
    for key,value in d.items():
        print key, value
    
    #  
    d['name'] = 'tom'
    
    d.update({'name':'tom'})  #        
    d.update( [ ('name','tom'), ('age',2) ] ) #        ,(key,value)
    d.update('name'='tom', 'age'=4)
    
    #  
    del d['key']
    value = d.pop('key') #      
    d.clear() #  
    
    #  
    d = {'a':10, 'c':8, 'b':9, 'd':7}
    #1)       key  
    keys = d.keys()
    keys.sort()
    for key in keys:
        print d.get(key)
       :
    10
    9
    8
    7
    
    #2)   value    
    sorted(d.items(), lambda x,y: cmp(x[1],y[1]))
       :
    [('d', 7), ('c', 8), ('b', 9), ('a', 10)]
    
    #3)        
    sorted(d)
    >>> print d
    {'a': 10, 'c': 8, 'b': 9, 'd': 7}
    
    #  
    dictionary   
    D.get(key, 0)       # dict[key],           ,0。[]      
    D.has_key(key)      #     TRUE,  FALSE
    D.keys()            #        
    D.values()          #             ,              
    D.items()           #              ,             ( , ),                        
    
    D.update(dict2)     #      
    D.popitem()         #    pair,        。      
    D.clear()           #    , del dict
    D.copy()            #    
    D.cmp(dict1,dict2)  #    ,(        、   、    )
                        #      1,   -1,    0
                
    dictionary   
    dict1 = dict        #  
    dict2=dict.copy()   #  ,      。

    5)集合(set)
    pythonの集合タイプは他の言語と類似しており、関係テストと重複要素の除去を含む無秩序な重複要素セットである.集合オブジェクトはunion(連合),intersection(交差),difference(差),sysmmetricdifference(対称差セット)などの数学演算もサポートし,我々の中学校数学学の集合と非常に似ている.
    #  
    a = [2,3,4,2,1]
    seta = set(a)
    >>> print seta
    set([1, 2, 3, 4]) #   2     
    
    setb = set('abracadabra')
    setc = set('alacazam')
    >>> print setc
    set(['a', 'c', 'z', 'm', 'l'])
    
    #  
    #1)in or not in
    x in seta
    x not in seta
    
    #2)          
    s.issubset(t) #     s           t  
    s <= t
    
    s.issuperset(t) #     t           s  
    s >= t
    
    #3)     
    s.union(t) #   
    s | t
    
    s.intersection(t) #  
    s & t
    
    s.difference(t) #       set    s      t       
    s - t
    
    s.symmetric_difference(t) #        set    s   t        
    s ^ t
    
    s.copy() #    set “s”      
    
    
    s.update(t) 
    s |= t
    
    s.intersection_update(t)
    s &= t
    
    s.difference_update(t)
    s -= t
    
    s.symmetric_difference_update(t)
    s ^= t
    
    s.add(x) #  set “s”      x
    s.remove(x) #  set “s”      x,          KeyError
    s.discard(x) #    set “s”      x,    
    s.pop() #       set “s”          ,         KeyError
    s.clear() #   set “s”