2012年4月27日 星期五

Python筆記 Set List Dictionary




集合 Set:

fruit = set(['apple','banana','tomato'])
vegetable = set (['carrot','tomato'])

print fruit | vegetable

print fruit - vegetable

print fruit & vegetable

print fruit ^ vegetable



set(['tomato', 'carrot', 'apple', 'banana'])
set(['apple', 'banana'])
set(['tomato'])
set(['carrot', 'apple', 'banana'])




List:

names = ['maca','Maca','Tony','Grace','Maca']

print names

print names.count('Maca')

names.sort()

print names

names.reverse()

print names

names.remove('Maca')

print names



['maca', 'Maca', 'Tony', 'Grace', 'Maca']
2
['Grace', 'Maca', 'Maca', 'Tony', 'maca']
['maca', 'Tony', 'Maca', 'Maca', 'Grace']
['maca', 'Tony', 'Maca', 'Grace']






Dictionary





di = {1:"HAHA",2:"LALA",3:"HOHO"}

print di[1]

di[1] = "MIMI"

print di[1]

di["A"] = "HEHE"

print di
print "-----------------------------------------------------"

print di.keys()

print di.values()

print "-----------------------------------------------------"
print di.pop("A")

print di

del di[2]

print di



HAHA
MIMI
{'A': 'HEHE', 1: 'MIMI', 2: 'LALA', 3: 'HOHO'}
-----------------------------------------------------
['A', 1, 2, 3]
['HEHE', 'MIMI', 'LALA', 'HOHO']
-----------------------------------------------------
HEHE
{1: 'MIMI', 2: 'LALA', 3: 'HOHO'}
{1: 'MIMI', 3: 'HOHO'}


沒有留言:

張貼留言