Агуулга

Python Tuples – Python Томьёоллууд #

mytuple = ("apple", "banana", "cherry")

Tuple – Томьёолол #

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.

Томьёоллууд олон зүйлсийг нэг хувьсагч дотор хадгалахад ашиглагддаг. Томьёолол нь Python-ний өгөгдлийн цуглуулгыг хадгалахад ашигладаг 4 өгөгдлийн төрлийн нэг бөгөөд үлдсэн 3 нь Жагсаалт (List), Багц (Set), Толь (Dictionary) юм. Томьёолол нь дараалсан, өөрчлөгдөшгүй цуглуулга юм. Томьёоллууд дугуй хаалтаар бичигддэг.

Example – Жишээ #

Create a Tuple:

Томьёолол үүсгэх:

thistuple = ("apple", "banana", "cherry")
print(thistuple)

Tuple Items – Томьёоллын зүйлс #

Tuple items are ordered, unchangeable, and allow duplicate values.

Томьёоллын зүйлс дараалсан, өөрчлөгдөшгүй бөгөөд давхардсан утгыг зөвшөөрдөг.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Томьёоллын зүйлс индексжсэн байдаг, эхний зүйл индекс [0], хоёр дахь зүйл индекс [1] гэх мэт.

Ordered – Дараалсан #

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Томьёоллууд дараалсан гэдэг нь зүйлсийн тодорхой дараалалтай бөгөөд тэрхүү дараалал нь өөрчлөгдөхгүй гэсэн үг.

Unchangeable – Өөрчлөгдөшгүй #

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Томьёоллууд өөрчлөгдөшгүй, энэ нь бид томьёоллыг үүсгэсний дараа зүйлсийг өөрчилж, нэмэх эсвэл устгаж чадахгүй гэсэн үг.

Allow Duplicates – Давхардлыг зөвшөөрнө #

Since tuples are indexed, they can have items with the same value:

Томьёоллууд индексжсэн учраас тэдгээр нь давхардсан утгатай зүйлсийг агуулж болно:

Example – Жишээ #

Tuples allow duplicate values:

Томьёоллууд давхардсан утгыг зөвшөөрнө:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)

Tuple Length – Томьёоллын урт #

To determine how many items a tuple has, use the len() function:

Томьёолол хэдэн зүйлс агуулж байгааг тодорхойлохын тулд len() функцийг ашиглана:

Example – Жишээ #

Print the number of items in the tuple:

Томьёоллын зүйлсийн тоог хэвлэнэ:

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

Create Tuple With One Item – Нэг зүйлтэй томьёолол үүсгэх #

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

Зөвхөн нэг зүйлтэй томьёолол үүсгэхийн тулд зүйлийн дараа таслал нэмэх хэрэгтэй, эс бөгөөс Python үүнийг томьёолол гэж танихгүй.

Example – Жишээ #

thistuple = ("apple",)
print(type(thistuple))
# томьёолол биш нь:
thistuple = ("apple")
print(type(thistuple))

Tuple Items – Data Types – Томьёоллын зүйлс – Өгөгдлийн төрлүүд #

Tuple items can be of any data type:

Томьёоллын зүйлст ямар ч өгөгдлийн төрөл байж болно:

Example – Жишээ #

tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple can contain different data types:

Нэг томьёолол өөр өөр өгөгдлийн төрлүүдийг агуулж болно:

Example – Жишээ #

A tuple with strings, integers and boolean values:

Томьёололд тэмдэгт мөр, бүхэл тоо болон буль утгууд байна:

tuple1 = ("abc", 34, True, 40, "male")

type()  #

From Python’s perspective, tuples are defined as objects with the data type ‘tuple’:

Python-ний хувьд томьёоллууд нь ‘tuple’ өгөгдлийн төрлийн объект байдлаар тодорхойлогддог:

<class ‘tuple’>

Example #

What is the data type of a tuple?

mytuple = ("apple", "banana", "cherry")
print(type(mytuple))

The tuple() Constructor – tuple() Конструктор #

It is also possible to use the tuple() constructor to make a tuple.

Мөн tuple() конструкторыг ашиглан томьёолол үүсгэх боломжтой.

Example – Жишээ #

Using the tuple() method to make a tuple:

tuple() аргачлалыг ашиглан томьёолол үүсгэх:

thistuple = tuple(("apple", "banana", "cherry")) # давхар хаалт байгааг анхаараарай
print(thistuple)

Python Collections (Arrays) – Python цуглуулгууд (Массивууд) #

There are four collection data types in the Python programming language:

Python программчлалын хэлэнд дөрвөн цуглуулгын өгөгдлийн төрлүүд байдаг:

  • List is a collection which is ordered and changeable. Allows duplicate members.

Жагсаалт (List) нь дараалсан, өөрчлөгдөх боломжтой цуглуулга юм. Давхардсан гишүүдийг зөвшөөрнө.

  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Томьёолол (Tuple) нь дараалсан, өөрчлөгдөшгүй цуглуулга юм. Давхардсан гишүүдийг зөвшөөрнө.

  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.

Багц (Set) нь дараалалгүй, өөрчлөгдөшгүй*, индексжээгүй цуглуулга юм. Давхардсан гишүүд байхгүй.

  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

Толь (Dictionary) нь дараалсан** болон өөрчлөгдөх боломжтой цуглуулга юм. Давхардсан гишүүд байхгүй.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

*Багцын зүйлс өөрчлөгдөхгүй, гэхдээ зүйлсийг устгаж болон нэмэж болно.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

**Python 3.7 хувилбараас хойш толь дараалсан. Python 3.6 болон өмнөх хувилбарууд дараалалгүй.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

Цуглуулгын төрлийг сонгохдоо тухайн төрлийн шинж чанаруудыг ойлгох хэрэгтэй. Тухайн өгөгдлийн багцыг хадгалах зөв төрлийг сонгох нь утгыг хадгалах болон үр ашгийг нэмэгдүүлэх эсвэл аюулгүй байдлыг хангах боломжтой юм.

Python – Access Tuple Items – Python – Томьёоллын зүйлсэд хандах
#

Access Tuple Items – Томьёоллын зүйлсэд хандах #

You can access tuple items by referring to the index number, inside square brackets:

Индексийн дугаарыг дөрвөлжин хаалтанд оруулан томьёоллын зүйлсэд хандаж болно:

Example – Жишээ #

Print the second item in the tuple:

Томьёоллын хоёр дахь зүйлийг хэвлэнэ:

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Note: The first item has index 0.

Анхаар: Эхний зүйл индекс 0-той.

Negative Indexing – Сөрөг индексжүүлэлт #

Negative indexing means start from the end.

Сөрөг индексжүүлэлт гэдэг нь төгсгөлөөс эхлэхийг хэлнэ.

-1 refers to the last item, -2 refers to the second last item etc.

-1 нь сүүлийн зүйлийг, -2 нь сүүлээсээ хоёр дахь зүйлийг гэх мэтчилэн заана.

Example – Жишээ #

Print the last item of the tuple:

Томьёоллын сүүлийн зүйлийг хэвлэ:

thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

Range of Indexes – Индексийн хязгаар #

You can specify a range of indexes by specifying where to start and where to end the range.

Индексийн хязгаар тодорхойлохдоо эхлэх болон төгсгөх хязгаарыг зааж өгч болно.

When specifying a range, the return value will be a new tuple with the specified items.

Хязгаар заах үед буцах утга нь заасан зүйлс байх шинэ томьёолол болно.

Example – Жишээ #

Return the third, fourth, and fifth item:

Гурав, дөрөв, тав дахь зүйлийг буцаа:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).

Анхаар: Хайлт 2-р индекст эхэлж (орсон), 5-р(орохгүй) индекст төгсөнө .

Remember that the first item has index 0.

Эхний индекс 0 гэдгийг санаарай.

By leaving out the start value, the range will start at the first item:

Эхлэх утгыг орхивол хүрээ нь эхний зүйлээс эхэлнэ:

Example – Жишээ #

This example returns the items from the beginning to, but NOT included, “kiwi”:

Энэ жишээ нь эхлэлээс “kiwi” хүртэлх зүйлсийг буцаана:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])

By leaving out the end value, the range will go on to the end of the tuple:

Төгсгөлийн утгыг орхивол хязгаар нь томьёоллын төгсгөл хүртэл үргэлжилнэ:

Example – Жишээ #

This example returns the items from “cherry” and to the end:

Энэ жишээ нь “cherry”-ээс төгсгөл хүртэлх зүйлсийг буцаана:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])

Range of Negative Indexes – Сөрөг индексийн хязгаар #

Specify negative indexes if you want to start the search from the end of the tuple:

Томьёоллын төгсгөлөөс хайлт хийхийг хүсвэл сөрөг индексийг зааж өгнө:

Example – Жишээ #

This example returns the items from index -4 (included) to index -1 (excluded)

Энэ жишээ нь -4-р индексээс (орсон)  -1-р индекс хүртэл (орохгүй) зүйлсийг буцаана:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

Check if Item Exists – Зүйл байгаа эсэхийг шалгах #

To determine if a specified item is present in a tuple use the in keyword:

Тодорхой нэг зүйл томьёололд байгаа эсэхийг тодорхойлохын тулд in түлхүүр үгийг ашиглана:

Example – Жишээ #

Check if “apple” is present in the tuple:

“apple” томьёололд байгаа эсэхийг шалга:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)

Python – Update Tuples – Python – Томьёоллыг шинэчлэх
#

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.

Томьёоллууд өөрчлөгдөшгүй, энэ нь томьёоллыг үүсгэсний дараа зүйлсийг өөрчилж, нэмэх, эсвэл устгаж чадахгүй гэсэн үг.

But there are some workarounds.

Гэхдээ зарим нэг арга замууд байдаг.

Change Tuple Values – Томьёоллын утгыг өөрчлөх #

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

Нэгэнт томьёолол үүсгэгдсэн бол түүний утгыг өөрчлөх боломжгүй. Томьёоллууд өөрчлөгдөшгүй, эсвэл өөрчлөлтгүй гэж нэрлэдэг.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Гэхдээ нэг арга зам бий. Томьёоллыг жагсаалт болгон хувиргаж, жагсаалтыг өөрчилж, дараа нь жагсаалтыг буцааж томьёолол болгон хувиргаж болно.

Example – Жишээ #

Convert the tuple into a list to be able to change it:

Томьёоллыг жагсаалт болгон хувиргаж өөрчлөх боломжтой болгоно:

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Add Items – Зүйл нэмэх #

Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items to a tuple.

Томьёоллууд өөрчлөгдөшгүй учраас append() мэт үүсгэдэг аргууд байхгүй, гэхдээ зүйлсийг нэмэх өөр аргууд байдаг.

1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.

1. Жагсаалт болгон хувиргах: Томьёоллыг өөрчлөх арга зам шиг, үүнийг жагсаалт болгон хувиргаж, зүйлээ нэмээд буцааж томьёолол болгон хувиргаж болно.

Example – Жишээ #

Convert the tuple into a list, add “orange”, and convert it back into a tuple:

Томьёоллыг жагсаалт болгон хувиргаж, “orange” нэмээд буцааж томьёолол болгон хувиргах:

thistuple = ("apple""banana""cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:

2. Томьёоллыг томьёололд нэмэх. Томьёоллыг томьёололд нэмэхийг зөвшөөрнө, тэгэхээр хэрэв та нэг зүйл нэмэхийг хүсвэл (эсвэл олон зүйл), шинэ томьёолол үүсгэж зүйлээ нэмээд байгаа томьёололдоо нэмнэ:

Example – Жишээ #

Create a new tuple with the value “orange”, and add that tuple:

“orange” утгатай шинэ томьёолол үүсгэж нэмнэ:

thistuple = ("apple""banana""cherry")
y = ("orange",)
thistuple += y
print(thistuple)

Note: When creating a tuple with only one item, remember to include a comma after the item, otherwise it will not be identified as a tuple.

Анхаар: Нэг зүйлтэй томьёолол үүсгэх үед зүйлийн дараа таслал оруулахаа мартуузай, эс бөгөөс үүнийг томьёолол гэж танихгүй.

Remove Items – Зүйл устгах #

Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:

Томьёоллууд өөрчлөгдөшгүй учраас зүйлсийг устгах боломжгүй, гэхдээ зүйлсийг өөрчлөх болон нэмэх үед хэрэглэсэн аргуудыг ашиглаж болно:

Example – Жишээ #

Convert the tuple into a list, remove “apple”, and convert it back into a tuple:

Томьёоллыг жагсаалт болгон хувиргаж, “apple”-г устгаад буцааж томьёолол болгон хувиргах:

thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Or you can delete the tuple completely:

Эсвэл бүхэлд нь томьёоллыг устгаж болно:

Example – Жишээ #

The del keyword can delete the tuple completely:

del түлхүүр үгийг ашиглан томьёоллыг бүхэлд нь устгах:

thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) # энэ нь алдаа гаргах болно, учир нь томьёолол байхгүй болсон

Python – Unpack Tuples – Python – Томьёоллыг задлах  #

Unpacking a Tuple – Томьёоллыг задлах #

When we create a tuple, we normally assign values to it. This is called “packing” a tuple:

Томьёолол үүсгэхдээ бид ерөнхийдөө түүнд утгыг оноодог. Үүнийг томьёололыг “багцлах” гэж нэрлэдэг:

Example – Жишээ #

Packing a tuple:

Багцлагдсан томьёолол:

fruits = ("apple", "banana", "cherry")

But, in Python, we are also allowed to extract the values back into variables. This is called “unpacking”:

Гэхдээ Python-д утгыг буцааж хувьсагчдад задлахыг зөвшөөрдөг. Үүнийг “задлах” гэж нэрлэдэг:

Example – Жишээ #

Unpacking a tuple:

Задалдаг томьёолол:

fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.

Анхаар: Хувьсагчдын тоо томьёолол дахь утгуудын тоотой таарч байх ёстой, эс тэгвээс та үлдсэн утгыг жагсаалт болгон цуглуулахын тулд од (*) тэмдгийг ашиглах хэрэгтэй.

Using Asterisk*Од тэмдэг (*) ашиглах: #

If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list:

Хэрэв хувьсагчдын тоо утгуудын тооноос бага байвал хувьсагчийн нэрэнд * тэмдгийг нэмээд утгуудыг хувьсагчид жагсаалт болгон оноож болно:

Example – Жишээ #

fruits = ("apple""banana""cherry""strawberry""raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)

If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

Хэрэв сүүлийнхээс өөр хувьсагчийн нэрэнд од нэмэгдсэн бол үлдсэн утгын тоо үлдсэн хувьсагчийн тоотой таарах хүртэл Python хувьсагчид утгуудыг онооно.

Example – Жишээ #

Add a list of values the “tropic” variable:

“tropic” хувьсагчид жагсаалтын утгууд нэм:

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)

Python – Loop Tuples – Python – Томьёоллуудыг давталттай гүйлгэх #

Loop Through a Tuple – Томьёоллоор давталт хийх #

You can loop through the tuple items by using a for loop.

for давталтыг ашиглан томьёоллын зүйлсээр давталт хийж болно.

 

Example – Жишээ #

Iterate through the items and print the values:

Зүйлүүдийг давтаж, утгыг хэвлэх:

thistuple = ("apple", "banana", "cherry")
for x in thistuple:
  print(x)

Learn more about for loops in Python For Loops Chapter.

Дэлгэрэнгүй мэдээллийг Python for давталтуудын бүлгээс үзнэ үү.

Loop Through the Index Numbers – Индексийн дугаараар давталт хийх #

You can also loop through the tuple items by referring to their index number.

Та мөн томьёоллын зүйлсээр индексийн дугаараар нь давталт хийж болно.

Use the range() and len() functions to create a suitable iterable.

range() болон len() функцуудыг ашиглан тохиромжтой давталт үүсгэнэ.

Example – Жишээ #

Print all items by referring to their index number:

Бүх зүйлийг индексийн дугаараар нь хэвлэх:

thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
  print(thistuple[i])

Using a While Loop – While давталт ашиглах #

You can loop through the tuple items by using a while loop.

Та while давталтыг ашиглан томьёоллын зүйлсээр давталт хийж болно.

Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by referring to their indexes.

len() функцыг ашиглан томьёоллын уртыг тодорхойлоод, дараа нь 0-ээс эхлэн томьёоллын зүйлсийг индексээр нь давталт хийнэ.

Remember to increase the index by 1 after each iteration.

Давталт бүрийн дараа индексийг 1-р нэмэгдүүлэхээ мартуузай.

Example – Жишээ #

thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
  print(thistuple[i])
  i = i + 1

Learn more about while loops in Python While Loops Chapter.

while давталтын дэлгэрэнгүй мэдээллийг Python while давталтуудын бүлгээс үзнэ үү.

Python – Join Tuples – Python – Холбох Томьёоллууд #

Join Two Tuples – Хоёр Томьёоллыг Холбох #

To join two or more tuples you can use the + operator:

Хоёр болон түүнээс олон томьёоллыг холбохын тулд + операторыг ашиглаж болно:

Example – Жишээ #

Join two tuples:

Хоёр томьёололыг холбох:

tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

Multiply Tuples – Томьёоллыг үржүүлэх #

If you want to multiply the content of a tuple a given number of times, you can use the * operator:

Хэрэв та томьёоллын агуулгыг тодорхой тооны удаа үржүүлэхийг хүсвэл * операторыг ашиглаж болно:

Example – Жишээ #

fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

Python – Tuple Methods – Python – Томьёоллын Аргууд  #

Tuple Methods – Томьёоллын Аргууд #

Python has two built-in methods that you can use on tuples.

Python-д томьёоллуудад ашиглаж болох хоёр суурь аргууд байдаг.

Method Description
count()

Returns the number of times a specified value occurs in a tuple

Томьёололд тодорхойлсон утга хэдэн удаа орсон болохыг буцаана

index()

Searches the tuple for a specified value and returns the position of where it was found

Томьёололд тодорхойлсон утгыг хайж, олдсон байрлалыг буцаана

Powered by BetterDocs

Leave a Reply