iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0

概觀(Overview)

和數學上的定義相同,無序性(unordered)元素不重複。通常用來做集合運算或者移除重複元素。

不支援sequence-like的操作,例如:取出其中某一個資料(indexed)或其中某一段資料(sliced)。

宣告(Declaration)

  • brackets (不能用來宣告empty set,會被當作dict)
  • set() (可以用來宣告empty set)
  • set comprehension
# 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

參考


上一篇
Day14-Tuple
下一篇
Day16-Built-in Types-Recap
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言