To’plamlar haqida ma’lumot. II. Asosiy qism


Download 136.13 Kb.
bet9/12
Sana04.02.2023
Hajmi136.13 Kb.
#1157765
1   ...   4   5   6   7   8   9   10   11   12
Bog'liq
d.dasturlash



ChainMap


ChainMap - bu bir nechta lug'atlarni saqlaydigan konteyner ma'lumotlar turi.
Ko'p hollarda sizda tegishli yoki shunga o'xshash lug'atlar bo'lishi mumkin, ularni birgalikda saqlashingiz mumkinChainMap
Foydalanadigan operatorda barcha elementlarni chop etishingiz mumkin ChainMap. Quyidagi kod xuddi shu narsani ko'rsatadi.map
# Creating a ChainMap from 3 dictionaries.
from collections import ChainMap
dic1={'red':5,'black':1,'white':2}
dic2={'chennai':'tamil','delhi':'hindi'}
dic3={'firstname':'bob','lastname':'mathews'}

my_chain = ChainMap(dic1,dic2,dic3)


my_chain.maps

#> [{'black': 1, 'red': 5, 'white': 2}, {'chennai': 'tamil', 'delhi': 'hindi'},{'firstname': 'bob', 'lastname': 'mathews'}]


Funktsiyadan foydalanib, zanjirli xaritadagi barcha lug'atlarning kalitlarini chop etishingiz mumkin.keys()
print(list(my_chain.keys()))

#> ['firstname', 'lastname', 'chennai', 'delhi', 'red', 'black', 'white']


Funktsiyadan foydalanib, zanjirli xaritadagi barcha lug'atlarning qiymatlarini chop etishingiz mumkin.
values()
print(list(my_chain.values()))
#> ['bob', 'mathews', 'tamil', 'hindi', 5, 1, 2]

ChainMap-da ortiqcha kalitlarga ega bo'lsak nima bo'ladi


2 ta lug'atda bir xil kalit bo'lishi mumkin. Quyidagi misolga qarang.
# Creating a chainmap whose dictionaries do not have unique keys
dic1 = {'red':1,'white':4}
dic2 = {'red':9,'black':8}
chain = ChainMap(dic1,dic2)
print(list(chain.keys()))

#>['black', 'red', 'white']


E'tibor bering, "qizil" takrorlanmaydi, u faqat bir marta chop etiladi

ChainMap-ga yangi lug'at qanday qo'shiladi


Usul yordamida ChainMap boshida yangi lug'at qo'shishingiz mumkin . Bu quyidagi kodda ko'rsatilgan.
new_child()
# Add a new dictionary to the chainmap through .new_child()
print('original chainmap', chain)

new_dic={'blue':10,'yellow':12}


chain=chain.new_child(new_dic)

print('chainmap after adding new dictioanry',chain)

#> original chainmap ChainMap({'red': 1, 'white': 4}, {'red': 9, 'black': 8})
#> chainmap after adding new dictioanry ChainMap({'blue': 10, 'yellow': 12}, {'red': 1, 'white': 4}, {'red': 9, 'black': 8})


Download 136.13 Kb.

Do'stlaringiz bilan baham:
1   ...   4   5   6   7   8   9   10   11   12




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling