# A yaratishning yana bir usulinamedtuple

 bet 4/12 Sana 04.02.2023 Hajmi 136.13 Kb. #1157765
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
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.