iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0
自我挑戰組

30天學會Python系列 第 12

Python - set 集合、dict 字典

集合

Set在Python中,集合Set為無序、不重複的集合

建立一個Set
可用 in 語法判斷 set 中是否擁有該元素,無序,語法為大括號{ }與逗點,構成

#%% Create a set
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)# fast membership testing
print('orange' in basket)
print('crabgrass' in basket)

Set 的運算
* a - b 差集
* a | b 聯集
* a & b 交集
* a ^ b 對稱差

#%% Set operation
a = set('abracadabra')
b = set('alacazam')
print("a: ", a) # unique letters in a
print("b: ", b) # unique letters in b
print("a - b: ", a - b) # letters in a but not in b
print("a | b: ", a | b) # letters in a or b or both
print("a & b: ", a & b) # letters in both a and b
print("a ^ b: ", a ^ b) # letters in a or b but not both

Set comprehesion

a = {x for x in 'abracadabra' if x not in 'abc'}

Reference
Python
Set
https://docs.python.org/3/tutorial/datastructures.html#sets
集合 (Wiki)
https://zh.wikipedia.org/wiki/%E9%9B%86%E5%90%88_(%E6%95%B0%E5%AD%A6)

字典 Dict

建立一個 Dict
python 中的字典可看為一個鍵 : 值配對的無序集合,可以用關鍵字 (Key) 進行索引建立一個字典,三種方法:
* {key: value, ...}
* dictonary 建構子 constructor
* dictionary comprehesion

#%% Create a dictionary
student = {'name': "John", 'age': 25, "courses": ['Math', 'CompSci']}
print("student: ",student)
d_contructor = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
print("d_contructor: ", d_contructor)
d_comprehesion = {x: x**2 for x in (2, 4, 6)}
print("d_comprehesion: ",d_comprehesion)

Dictionary method
dict class 內建的 method
* items()
* Keys()
* values()
* update()
* pop()

#%% Dict method# items
print("items(): ", student.items())# keys()
print("Keys(): ", student.keys())# values()
print("values(): ", student.values())# Change return value if get nothing in dict
print("student: ", student)
print(student.get('phone', 'Not found'))# update value (1)
student['phone'] = '555-5555'
student['name'] = 'Jane'# or update value (2)
student.update({'name': 'Jane', 'age': 26, 'phone': '555-5555'})
print(student)# delete : key (1)
del student['age']
print(student)# delete : pop key-value (2)
student.update({'name': 'Jane', 'age': 26, 'phone': '555-5555'})
age = student.pop('age')
print(age)
print(student)

Loop dictionary

#%% loop dictionary
for key, value in student.items():
    print(key, value)

Reference

https://docs.python.org/3.7/library/stdtypes.html#mapping-types-dict
Python Dictionary
https://docs.python.org/3/tutorial/datastructures.html#dictionaries


上一篇
Python - tuple 元組
下一篇
Python - for loop/ while loop 迴圈
系列文
30天學會Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言