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


A yaratishning yana bir usulinamedtuple


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

A yaratishning yana bir usulinamedtuple


Shu bilan bir qatorda, bo'sh joy bilan ajratilgan fayl nomlari o'rniga maydon nomlari ro'yxatini o'tkazishingiz mumkin.
Keling, bir misolni ko'rib chiqaylik.
# Creating namedtuple by passing fieldnames as a list of strings
book = namedtuple('book',['price','no_of_pages','author'])

harry_potter = book('500','367','JK ROWLING')


pride_and_prejudice = book('300','200','jane_austen')
tale = book('199','250','christie')

print('Price of pride and prejudice is ',pride_and_prejudice.price)


print('author of harry potter is',harry_potter.author)

#> Price of pride and prejudice is 300


#> author of harry potter is JK ROWLING
a dagi elementlarga namedtupleham indeks, ham identifikator orqali kirish mumkin.
print(tale[1])
#> 250

Nima uchun lug'atda nametuple dan foydalaning


Ularning asosiy afzalligi shundaki namedtuple, ular ekvivalent lug'atga qaraganda kamroq joy/xotira oladi.
Shunday qilib, katta ma'lumotlarga ega bo'lgan holda, nomli to'plar samarali bo'ladi.
Men buni quyidagi misolda ko'rsataman.
# Create a dict and namedtuple with same data and compare the size
import random
import sys


# Create Dict
dicts = {'numbers_1': random.randint(0, 10000),'numbers_2':random.randint(5000,10000)}
print('Size or space occupied by dictionary',sys.getsizeof(dicts))

# converting same dictionary to a namedtuple


data=namedtuple('data',['numbers_1','numbers_2'])
my_namedtuple= data(**dicts)
print('Size or space occupied by namedtuple',sys.getsizeof(my_namedtuple))
#> Size or space occupied by dictionary 240
#> Size or space occupied by namedtuple 64
Yuqoridagi kodni bajarib, siz nomli tuple '64' o'lchamiga ega ekanligini topasiz, lug'at esa ancha kattaroq '240' baytni egallaydi. Bu deyarli 4 baravar kichik xotira.
Ko'p sonli bunday ob'ektlarni boshqarish uchun kengaytirilganda effektni tasavvur qilishingiz mumkin.

Download 136.13 Kb.

Do'stlaringiz bilan baham:
1   2   3   4   5   6   7   8   9   ...   12




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