2012年9月13日 星期四

Python List , Set , Dictionary , Tuple Operation Practice

'''
Created on 2012/9/12
Fourth Python program - List , Set , Dictionary , Tuple
@author: AJ0549
'''

if __name__ == '__main__':
    
    list1=[] # create empty list
    list1.append(6) # add element
    list1.append("String") # add element
    list1.append(True) # add element
    print("list:",list1,list1[0:2])
    list2=[[0,1,2],[5,4,3],[1,3,4]] # two array list
    print("list:",list2,list2[0:2])
    list3=list2[0:2] #extrat element to create new list
    print("list:",list3[1] in list2,list3 in list2)
    list2.sort() # list sort (same type)
    print(list2)
    
    set1={6,"string",True} #create set
    set2={6,2,3}
    print("set:",True in set1)
    print("set:",set1|set2) #Union operator
    print("set:",set1&set2) #Intersection operation
    print("set:",set1-set2) #Difference operation
    print("set:",set1^set2) #XOR operation
    print("set:",set1>set2,set2<set1) #sub set test
    set1.add("LOL") # add element
    print("set:",set1)
    set3=set() #create empty set
    set3.add(6)
    print("set:",set3,set1<set3,set1>set3)

    pass1 = {"A":1,"B":2} # create dictionary (same as dict)
    pass2=dict(A=1,B=2)                       
    print("dict:",pass1,pass2)
    pass1["A"]=9
    print("dict:",pass1["A"])
    del(pass1["A"]) #del elements
    print("dict:",pass1)
    pass1.update({"A":6})
    print("dict:",pass1)
    print("dict:",pass1.items(),pass1.keys(),pass1.values())
    
    tup1=(1,2,3,4) # create tuple
    print("tuple:",tup1,tup1[2])
    tup2=([1,2],[3,4]) #create array tuple
    print("tuple:",tup2,tup2[0],tup2[0][1])
    tup2[0][1]=9
    print("tuple:",tup2)
    try:
        tup2[0]=[7,8]
    except:
        print("tuple:","Tuple is Immutable")
執行後
('list:', [6, 'String', True], [6, 'String'])
('list:', [[0, 1, 2], [5, 4, 3], [1, 3, 4]], [[0, 1, 2], [5, 4, 3]])
('list:', True, False)
[[0, 1, 2], [1, 3, 4], [5, 4, 3]]
('set:', True)
('set:', set([True, 2, 3, 'string', 6]))
('set:', set([6]))
('set:', set([True, 'string']))
('set:', set([True, 2, 3, 'string']))
('set:', False, False)
('set:', set(['LOL', True, 'string', 6]))
('set:', set([6]), False, True)
('dict:', {'A': 1, 'B': 2}, {'A': 1, 'B': 2})
('dict:', 9)
('dict:', {'B': 2})
('dict:', {'A': 6, 'B': 2})
('dict:', [('A', 6), ('B', 2)], ['A', 'B'], [6, 2])
('tuple:', (1, 2, 3, 4), 3)
('tuple:', ([1, 2], [3, 4]), [1, 2], 2)
('tuple:', ([1, 9], [3, 4]))
('tuple:', 'Tuple is Immutable')

沒有留言:

張貼留言