和數學上的定義相同,無序性(unordered)
且元素不重複
。通常用來做集合運算或者移除重複元素。
不支援sequence-like
的操作,例如:取出其中某一個資料(indexed)或其中某一段資料(sliced)。
# empty set
demo = {} # it will be dictionary
print(demo)
print( "type of demo: {}".format( type(demo) ) )
print( "len of demo: {}".format( len(demo) ) )
print( "id of demo: {}".format( id(demo) ) )
# {}
# type of demo: <class 'dict'>
# len of demo: 0
# id of demo: 140482058356200
demo2 = set()
print(demo2)
print( "type of demo2: {}".format( type(demo2) ) )
print( "len of demo2: {}".format( len(demo2) ) )
print( "id of demo2: {}".format( id(demo2) ) )
# set()
# type of demo2: <class 'set'>
# len of demo2: 0
# id of demo2: 140482058370856
# multiple elements
demo3 = {'python', 'java', 'c', 'c++', 'c#', 'go', 'php', 'python', 'java'}
print(demo3)
print( "type of demo3: {}".format( type(demo3) ) )
print( "len of demo3: {}".format( len(demo3) ) )
# {'php', 'go', 'python', 'c++', 'c', 'c#', 'java'}
# type of demo3: <class 'set'>
# len of demo3: 7
# set comprehension
d_list = [0, 1, 1, 2 ,3 ,5, 8, 13, 21]
demo4 = {x for x in d_list if x % 3 == 0}
print(demo4)
print( "type of demo4: {}".format( type(demo4) ) )
# {0, 3, 21}
# type of demo4: <class 'set'>
操作層面分為集合運算、走訪、判斷元素是否存在於集合內
交集、聯集、差集和XOR
zoo_taipei = {'bear', 'fish', 'wolf', 'deer', 'tiger'}
zoo_kaohsiung = {'lion', 'tiger', 'bear', 'hipo', 'giraffe'}
# intersection
common_animals = zoo_taipei & zoo_kaohsiung
print(common_animals)
# {'bear', 'tiger'}
# union
all_animals = zoo_taipei | zoo_kaohsiung
print(all_animals)
# {'fish', 'hipo', 'deer', 'lion', 'bear', 'giraffe', 'tiger', 'wolf'}
# difference
taipei_uniq_animals = zoo_taipei - zoo_kaohsiung
print(taipei_uniq_animals)
# {'fish', 'wolf', 'deer'}
kaohsiung_uniq_animals = zoo_kaohsiung - zoo_taipei
print(kaohsiung_uniq_animals)
# {'lion', 'giraffe', 'hipo'}
# symmetric difference
# animals in taipei or kaohsiung but not both
new_animals = zoo_taipei ^ zoo_kaohsiung
print(new_animals)
# {'fish', 'deer', 'hipo', 'lion', 'wolf', 'giraffe'}
# NOt support indexed
try:
print(zoo_taipei[0])
except TypeError as e:
print( "Type Error: {0}".format(e) )
# Type Error: 'set' object does not support indexing
# iteration
for animal in zoo_taipei:
print( "animal:{}".format(animal) )
# animal:fish
# animal:deer
# animal:bear
# animal:tiger
# animal:wolf
# include membership testing
if 'tiger' in zoo_kaohsiung:
print( "tiger in kaohsiung" )
if 'lion' in zoo_taipei:
print( "lion in taipei" )
else:
print( "lion NOT in taipei" )
# tiger in kaohsiung
# lion NOT in taipei