Python - 字典、集合、元組

WBOY
發布: 2024-08-12 22:35:37
原創
498 人瀏覽過

這三個都是Python中不同類型的資料結構。這用於存儲不同的數據集合。根據我們要求的用例,我們需要在其中進行選擇。

Python - Dictionary, Set, Tuple

字典(dict):

  1. 字典是鍵值對的集合,其中每個鍵與一個值關聯
  2. 可以根據鍵值檢索資料(基於鍵的搜尋),因為鍵要求唯一。
  3. 字典在 3.7 之前都是無序的,值可以改變。鍵名不能直接更改

文法:
庫存= {'蘋果':20,'香蕉':30,'胡蘿蔔':15,'牛奶':15}
print('t1.庫存物品', inventory)

可以使用下列語法新增另一個值/修改現有鍵的值

庫存['雞蛋'] = 20
庫存['麵包'] = 25
print('t2.更新的庫存物品', inventory)
庫存['雞蛋']=庫存['雞蛋']+5
print('t3.補貨後', 庫存)

  • 可以使用 del 關鍵字從 dict 中刪除資料。
  • 可以使用 in 關鍵字檢查資料是否存在。結果將為布林值。

刪除庫存['紅蘿蔔']
del inventory['麵包']
print('t4.刪除後更新庫存', inventory)

is_bananas_in_inventory = 庫存中的「香蕉」
print('t5a.庫存中有香蕉嗎', is_bananas_in_inventory)
is_oranges_in_inventory = 庫存中的「橘色」
print('t5b.庫存是否有橘色', is_oranges_in_inventory)

備註:
另外 dict.items() 會將字典中的每個項目作為元組(如鍵值對)給出。透過使用 list(dict.items()) 我們也可以獲得列表形式的資料。使用 for 迴圈和 if 條件,我們可以存取特定的鍵並對該資料執行所需的操作

for product, product_count in inventory.items():
    print('\t\t6. Product:', product, 'count is:', product_count)
print ('\t7. Iterating inventory gives tuple:', inventory.items())

#Printing only egg count(Value of key 'egg') by itearting dict
for product, product_count in inventory.items():
    if product is 'egg':
        print('\t8. Product:', product, ' its count is:', product_count)

#Printing egg count (value of key 'egg')
print('\t9. Count of apple',inventory['egg'])
登入後複製
Output:
        1. Inventory items {'apple': 20, 'Banana': 30, 'carrot': 15, 'milk': 15}
        2. Updated Inventory items {'apple': 20, 'Banana': 30, 'carrot': 15, 'milk': 15, 'egg': 20, 'bread': 25}
        3. After restocking {'apple': 30, 'Banana': 30, 'carrot': 15, 'milk': 15, 'egg': 25, 'bread': 25}
        4. Updated Inventory after delete {'apple': 30, 'Banana': 30, 'milk': 15, 'egg': 25}
        5a. Is banana in inventory True
        5b. Is Orange in inventory False
                6. Product: apple count is: 30
                6. Product: Banana count is: 30
                6. Product: milk count is: 15
                6. Product: egg count is: 25
        7. Iterating inventory gives tuple: dict_items([('apple', 30), ('Banana', 30), ('milk', 15), ('egg', 25)])
        8. Product: egg  its count is: 25
        9. Count of apple 25
登入後複製

設定:
集合是唯一元素的無序集合。集合是可變的,但它們不允許重複的元素。

文法:
botanical_garden = {'玫瑰', '蓮花', '百合'}
botanical_garden.add('茉莉花')
botanical_garden.remove('玫瑰')
is_present_Jasmine = 植物園中的「茉莉花」

上面我們可以看到定義了一個集合,增加了一個值並刪除了它。如果我們在集合中加入相同的元素,則會出錯。

我們也可以比較類似維恩圖的兩個集合。例如兩個資料集的並集、差集、交集。

botanical_garden = {'Tuple', 'rose', 'Lily', 'Jasmine', 'lotus'}
rose_garden = {'rose', 'lotus', 'Hybiscus'}

common_flower= botanical_garden.intersection(rose_garden)
flowers_only_in_bg = botanical_garden.difference(rose_garden)
flowers_in_both_set = botanical_garden.union(rose_garden)

Output will be a set by default. 
If needed we can typecase into list using list(expression)
登入後複製

元組:
元組是不可變的有序元素集合,這意味著它在創建後就無法更改。

文法:

ooty_trip = ('Ooty', '2024-1-1', 'Botanical_Garden')
munnar_trip = ('Munar', '2024-06-06', 'Eravikulam National Park')
germany_trip = ('Germany', '2025-1-1', 'Lueneburg')
print('\t1. Trip details', ooty_trip, germany_trip)

#Accessing tuple using index
location = ooty_trip[0]
date = ooty_trip[1]
place = ooty_trip[2]

print(f'\t2a. Location: {location} Date: {date} Place: {place} ')

location, date, place =germany_trip # Assinging a tuple to 3 different variables
print(f'\t2b. Location: {location} Date: {date} Place: {place} ')

print('\t3. The count of ooty_trip is ',ooty_trip.count)

Output:
   1. Trip details ('Ooty', '2024-1-1', 'Botanical_Garden') ('Germany', '2025-1-1', 'Lueneburg')
   2a. Location: Ooty Date: 2024-1-1 Place: Botanical_Garden
   2b. Location: Germany Date: 2025-1-1 Place: Lueneburg
   3. The count of ooty_trip is  <built-in method count of tuple object at 0x0000011634B3DBC0>

登入後複製

可以使用索引存取元組。元組的值可以輕鬆地分配給多個變數。我們可以組合兩個元組來建立另一個元組。但元組不能修改。

以上是Python - 字典、集合、元組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!