Агуулга

Python Lists – Python Жагсаалтууд #

mylist = ["apple", "banana", "cherry"]

List – Жагсаалт #

Lists are used to store multiple items in a single variable.

Жагсаалтууд нь нэг хувьсагчид олон зүйлсийг хадгалахад ашиглагддаг.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Жагсаалтууд нь Python-д өгөгдлийн цуглуулгыг хадгалахад ашиглагддаг дөрвөн төрлийн өгөгдлийн төрөл юм. Бусад гурван төрөл нь Tuple, Set, Dictionary бөгөөд бүгд өөр өөр онцлог, хэрэглээтэй.

Lists are created using square brackets:

Жагсаалтууд дөрвөлжин хаалтаар үүсгэгддэг.

Example – Жишээ #

Create a List:

Жагсаалт үүсгэх:

thislist = ["apple", "banana", "cherry"]
print(thislist)

List Items – Жагсаалтын зүйлс #

List items are ordered, changeable, and allow duplicate values.

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

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

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

Ordered – Дараалалтай #

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

Жагсаалт дараалалтай гэж оруулахад, зүйлс тодорхой дараалалтай байдаг ба тэр дараалал өөрчлөгдөхгүй гэсэн үг юм.

If you add new items to a list, the new items will be placed at the end of the list.

Хэрэв жагсаалтанд шинэ зүйлс нэмбэл, шинэ зүйлс жагсаалтын төгсгөлд байрлана.

Note: There are some list methods that will change the order, but in general: the order of the items will not change.

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

Changeable – Өөрчлөгдөх боломжтой #

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

Жагсаалт өөрчлөгдөх боломжтой, энэ нь жагсаалт үүсгэсний дараа зүйлсийг өөрчлөх, нэмэх, хасах боломжтой гэсэн үг юм.

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

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

Жагсаалт индексжүүлэгддэг тул, жагсаалтанд ижил утгатай зүйлс байж болно:

Example – Жишээ #

Lists allow duplicate values:

Жагсаалт давхардсан утгуудыг зөвшөөрдөг:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

List Length – Жагсаалтын урт #

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

Жагсаалт хэдэн зүйлтэйг тодорхойлоход len() функцыг ашигла:

Example – Жишээ #

Print the number of items in the list:

Жагсаалтанд байгаа зүйлсийн тоог хэвлэ:

thislist = ["apple", "banana", "cherry"]
print(len(thislist))

List Items – Data Types – Жагсаалтын зүйлс – Өгөгдлийн төрлүүд #

List items can be of any data type:

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

Example – Жишээ #

String, int and boolean data types:

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

list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Жагсаалт нь өөр өөр өгөгдлийн төрлүүдийг агуулж болно:

Example – Жишээ #

A list with strings, integers and boolean values:

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

list1 = ["abc", 34, True, 40, "male"]

type() #

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

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

<class ‘list’>

Example – Жишээ #

What is the data type of a list?

Жагсаалтын өгөгдлийн төрөл юу вэ?

mylist = ["apple", "banana", "cherry"]
print(type(mylist))

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

It is also possible to use the list() constructor when creating a new list.

Шинэ жагсаалт үүсгэхдээ list() конструкторыг ашиглах боломжтой.

Example – Жишээ #

Using the list() constructor to make a List:

list() конструктор ашиглан жагсаалт үүсгэх:

thislist = list(("apple", "banana", "cherry")) # давхар хаалтыг анхаараарай
print(thislist)

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.

*Set-ийн зүйлс өөрчлөгдөх боломжгүй боловч та хүссэн үедээ зүйлсийг хасах болон/эсвэл нэмэх боломжтой.

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

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

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 List Items – Python – Жагсаалтын Зүйлсэд Хандах #

Access Items – Зүйлсэд хандах #

List items are indexed and you can access them by referring to the index number:

Жагсаалтын зүйлс индексжүүлэгддэг ба та тэдгээрт индексийн дугаарыг зааж хандах боломжтой:

Example – Жишээ #

Print the second item of the list:

Жагсаалтын хоёр дахь зүйлийг хэвлэх:

thislist = ["apple", "banana", "cherry"]
print(thislist[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 list:

Жагсаалтын сүүлчийн зүйлийг хэвлэх:

thislist = ["apple", "banana", "cherry"]
print(thislist[-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 list with the specified items.

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

Example – Жишээ #

Return the third, fourth, and fifth item:

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

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[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 including, “kiwi”:

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

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] # Үр дүн: ['cherry', 'orange', 'kiwi', 'melon', 'mango']
print(thislist[:4])

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

Дуусах утгыг орхисноор хязгаар жагсаалтын төгсгөл хүртэл үргэлжилнэ:

Example – Жишээ #

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

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

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:]) # Үр дүн: ['cherry', 'orange', 'kiwi', 'melon', 'mango']

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

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

Хэрэв жагсаалтын төгсгөлөөс хайхыг хүсвэл сөрөг индексүүдийг тодорхойл:

Example – Жишээ #

This example returns the items from “orange” (-4) to, but NOT including “mango” (-1):

Энэ жишээ нь “orange” (-4) –аас “mango” (-1)-г оруулахгүйгээр буцаана:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1]) # Үр дүн: ['orange', 'kiwi', 'melon']

Check if Item Exists – Зүйлс Байгаа Эсэхийг Шалгах #

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

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

Example – Жишээ #

Check if “apple” is present in the list:

“apple” жагсаалтанд байгаа эсэхийг шалгах:

thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")

Python – Change List Items – Python – Жагсаалтын Зүйлсийг Өөрчлөх #

Change Item Value – Зүйлийн Утгыг Өөрчлөх #

To change the value of a specific item, refer to the index number:

Тодорхой зүйлийн утгыг өөрчлөхийн тулд индексийн дугаарыг заана:

Example – Жишээ #

Change the second item:

Хоёр дахь зүйлийг өөрчлөх:

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

Change a Range of Item Values – Зүйлсийн Утгын Хязгаар Өөрчлөх #

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:

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

Example – Жишээ #

Change the values “banana” and “cherry” with the values “blackcurrant” and “watermelon”:

“banana” ба “cherry” утгуудыг “blackcurrant” ба “watermelon” утгуудаар өөрчлөх:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Хэрэв солихоосоо илүү олон зүйл оруулбал, шинэ зүйлсийг заасан байршилд оруулж, үлдсэн зүйлсүүд зохих ёсоор шилжинэ:

Example – Жишээ #

Change the second value by replacing it with two new values:

Хоёр дахь утгыг хоёр шинэ утгаар солих:

thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

Note: The length of the list will change when the number of items inserted does not match the number of items replaced.

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

If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Хэрэв та солихоосоо цөөн зүйл оруулбал, шинэ зүйлсийг заасан байршилд оруулж, үлдсэн зүйлсүүд зохих ёсоор шилжинэ:

Example – Жишээ #

Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items – Зүйлсийг Оруулах #

To insert a new list item, without replacing any of the existing values, we can use the insert() method.

Жагсаалтад шинэ зүйлсийг оруулахын тулд одоо байгаа утгуудыг солихгүйгээр insert() аргыг ашиглаж болно.

The insert() method inserts an item at the specified index:

insert() арга нь заасан индекс дээр зүйлсийг оруулна:

Example – Жишээ #

Change the second value by replacing it with two new values:

Хоёр дахь утгыг хоёр шинэ утгаар солих:

thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

Note: As a result of the example above, the list will now contain 4 items.

Тэмдэглэл: Дээрх жишээний үр дүнд жагсаалт одоо 4 зүйл агуулна.

Python – Add List Items – Жагсаалтын Зүйлсийг Нэмэх #

Append Items – Зүйлсийг Нэмэх #

To add an item to the end of the list, use the append() method:

Жагсаалтын төгсгөлд зүйлс нэмэхийн тулд append() аргыг ашиглана:

Example – Жишээ #

Using the append() method to append an item:

append() аргыг ашиглан зүйлс нэмэх:

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

Insert Items – Зүйлс Оруулах #

To insert a list item at a specified index, use the insert() method.

Жагсаалтын зүйлсийг заасан индекс дээр оруулахын тулд insert() аргыг ашиглана.

The insert() method inserts an item at the specified index:

insert() арга нь заасан индекс дээр зүйлсийг оруулна:

Example – Жишээ #

Insert an item as the second position:

Зүйлсийг хоёр дахь байршилд оруулах:

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Note: As a result of the examples above, the lists will now contain 4 items.

Тэмдэглэл: Дээрх жишээнүүдийн үр дүнд жагсаалтууд одоо 4 зүйл агуулна.

Extend List – Жагсаалтыг Өргөтгөх #

To append elements from another list to the current list, use the extend() method.

Өөр жагсаалтын элементүүдийг одоогийн жагсаалтанд нэмэхийн тулд extend() аргыг ашиглана.

Example – Жишээ #

Add the elements of tropical to thislist:

тропикал элементүүдийг энэ жагсаалт-нд нэмэх:

thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

The elements will be added to the end of the list.

Элементүүд жагсаалтын төгсгөлд нэмэгдэнэ.

Add Any Iterable – Аль Нэг Дамжуулагчийг Нэмэх #

The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).

extend() арга нь жагсаалтуудыг нэмэх шаардлагагүй, та аль нэг дамжуулагч объект (tuples, sets, dictionaries гэх мэт) нэмж болно.

Example – Жишээ #

Add elements of a tuple to a list:

tuple элементүүдийг жагсаалтанд нэмэх:

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

Python – Remove List Items – Python – Жагсаалтын Зүйлсийг Устгах #

Remove Specified Item – Тодорхой Зүйлсийг Устгах #

The remove() method removes the specified item.

remove() арга нь заасан зүйлсийг устгана.

Example – Жишээ #

Remove “banana”:

“banana”-г устгах:

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

If there are more than one item with the specified value, the remove() method removes the first occurance:

Хэрэв заасан утгатай олон зүйл байвал remove() арга нь эхний тохиолдлыг устгана:

Example – Жишээ #

Remove the first occurance of “banana”:

“banana”-гийн эхний тохиолдлыг устгах:

thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)

Remove Specified Index – Тодорхой Индексийг Устгах #

The pop() method removes the specified index.

pop() арга нь заасан индексийг устгана.

Example – Жишээ #

Remove the second item:

Хоёр дахь зүйлийг устгах:

thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

If you do not specify the index, the pop() method removes the last item.

Хэрэв индексийг заагаагүй бол pop() арга нь сүүлийн зүйлийг устгана.

Example – Жишээ #

Remove the last item:

Сүүлийн зүйлийг устгах:

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

The del keyword also removes the specified index:

del түлхүүр үг нь мөн заасан индексийг устгана:

Example – Жишээ #

Remove the first item:

Эхний зүйлийг устгах:

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

The del keyword can also delete the list completely.

del түлхүүр үг нь мөн жагсаалтыг бүрэн устгаж болно.

Example – Жишээ #

Delete the entire list:

Бүх жагсаалтыг устгах:

thislist = ["apple", "banana", "cherry"]
del thislist

Clear the List – Жагсаалтыг Цэвэрлэх #

The clear() method empties the list.

clear() арга нь жагсаалтыг хоослоно.

The list still remains, but it has no content.

Жагсаалт хэвээр үлдэх боловч дотор нь юм байхгүй  болно.

Example – Жишээ #

Clear the list content:

Жагсаалтын агуулгыг цэвэрлэх:

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Python – Loop Lists – Python – Жагсаалтыг Давталтанд Оруулах #

Loop Through a List – Жагсаалтыг давталтанд оруулах #

You can loop through the list items by using a for loop:

Жагсаалтын зүйлсийг for давталтаар дамжуулж болно:

Example – Жишээ #

Print all items in the list, one by one:

Жагсаалтын бүх зүйлийг нэг нэгээр нь хэвлэх:

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

Learn more about for loops in our Python For Loops Chapter.

Python For Loops бүлгээс for давталтын талаар дэлгэрэнгүй уншина уу.

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

You can also loop through the list 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:

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

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

The iterable created in the example above is [0, 1, 2].

Дээрх жишээнд үүсгэсэн дамжуулагч нь [0, 1, 2] байна.

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

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

Жагсаалтын зүйлсийг while давталтаар дамжуулж болно.

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

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

Remember to increase the index by 1 after each iteration.

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

Example – Жишээ #

Print all items, using a while loop to go through all the index numbers

Бүх зүйлийг хэвлэх, while давталтыг ашиглан бүх индексийн дугааруудаар дамжуулах:

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

Learn more about while loops in our Python While Loops Chapter.

Python While Loops бүлгээс while давталтын талаар дэлгэрэнгүй уншина уу.

Looping Using List Comprehension – Жагсаалтыг Компрехэнс ашиглан давталтанд оруулах #

List Comprehension offers the shortest syntax for looping through lists:

Жагсаалтын дамжуулалтанд хамгийн богино өгүүлбэр зүйг санал болгодог:

Example – Жишээ #

A short hand for loop that will print all items in a list:

Жагсаалтан дахь бүх зүйлийг хэвлэх богино болгосон for давталт:

thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

Python – List Comprehension – Python – Жагсаалтын Компрехэнс #

List Comprehension – Жагсаалтын Компрехэнс #

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Компрехэнс нь одоо байгаа жагсаалтын утгуудаас шинэ жагсаалт үүсгэхийг хүсэх үед богино өгүүлбэр зүйг санал болгодог.

Example:

Жишээ:

Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name.

Жимсний жагсаалтын үндсэн дээр, нэрэнд нь “a” үсэг орсон жимснүүдийг шинэ жагсаалтанд хүсэж байна.

Without list comprehension you will have to write a for statement with a conditional test inside:

Компрехэнсгүйгээр for хэллэг дотор нөхцлийг нь шалгаж бичих хэрэгтэй болно:

Example – Жишээ #

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

With list comprehension you can do all that with only one line of code:

Компрехэнс ашиглан та бүх зүйлийг нэг мөр кодоор хийх боломжтой:

Example – Жишээ #

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

The Syntax – Дүрэм #

newlist = [expression for item in iterable if condition == True]

newlist = [илэрхийлэл for зүйл in тоолуур if нөхцөл == True]

The return value is a new list, leaving the old list unchanged.

Буцах утга нь шинэ жагсаалт бөгөөд хуучин жагсаалт өөрчлөгдөөгүй хэвээр үлдэнэ.

Condition – Нөхцөл #

The condition is like a filter that only accepts the items that valuate to True.

Нөхцөл нь зөвхөн True утгатай зүйлсийг хүлээн авдаг шүүлтүүртэй адил юм.

Example – Жишээ #

Only accept items that are not “apple”:

“apple” биш зүйлсийг л хүлээн авах:

newlist = [x for x in fruits if x != "apple"]

The condition if x != “apple”  will return True for all elements other than “apple”, making the new list contain all fruits except “apple”.

Хэрэв x != “apple” нөхцөл нь “apple”-с бусад бүх элементүүдийн хувьд True утгыг буцаах бөгөөд шинэ жагсаалт нь “apple” байхгүй бүх жимсүүд багтсан байна.

The condition is optional and can be omitted:

Нөхцөл нь сонголттой бөгөөд алгасах боломжтой:

Example – Жишээ #

With no if statement:

if байхгүйгээр:

newlist = [x for x in fruits]

Iterable – Дамжуулагч #

The iterable can be any iterable object, like a list, tuple, set etc.

Дамжуулагч нь list, tuple, set гэх мэт аль ч дамжуулагч объект байж болно.

Example – Жишээ #

You can use the range() function to create an iterable:

Дамжуулагч үүсгэхийн тулд range() функцыг ашиглаж болно:

newlist = [x for x in range(10)]

Same example, but with a condition:

Ижил жишээ, гэхдээ нөхцөлтэй:

Example – Жишээ #

Accept only numbers lower than 5:

5-аас бага тоонуудыг хүлээн авах:

newlist = [x for x in range(10) if x < 5]

Expression – Илэрхийлэл #

The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list:

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

Example – Жишээ #

Set the values in the new list to upper case:

Шинэ жагсаалтын утгыг том үсгээр тогтоох:

newlist = [x.upper() for x in fruits]

You can set the outcome to whatever you like:

Үр дүнг хүссэнээрээ тогтоож болно:

Example – Жишээ #

Set all values in the new list to ‘hello’:

Шинэ жагсаалтын бүх утгыг ‘hello’ болгох:

newlist = ['hello' for x in fruits]

The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome:

Илэрхийлэл нь нөхцөл агуулж болно, гэхдээ шүүлтүүр шиг биш, харин үр дүнг удирдах арга болох юм:

Example – Жишээ #

Return “orange” instead of “banana”:

“banana”-ны оронд “orange” буцаах:

newlist = [x if x != "banana" else "orange" for x in fruits]

The expression in the example above says:

Дээрх жишээний илэрхийлэл нь:

“Return the item if it is not banana, if it is banana return orange”.

“Хэрвээ гадил биш бол буцааж өгч, гадил бол жүрж болгож буцаа”.

Python – Sort Lists – Python – Жагсаалтыг Эрэмбэлэх #

Sort List Alphanumerically – Жагсаалтыг Цагаан Толгойн болон Тооны Эрэмбээр Эрэмбэлэх #

List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

Жагсаалтын объектийг цагаан толгойн болон тооны эрэмбээр өсөх эрэмбэлэх sort() арга байдаг:

Example – Жишээ #

Sort the list alphabetically:

Жагсаалтыг цагаан толгойн эрэмбээр эрэмбэлэх:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Example – Жишээ #

Sort the list numerically:

Жагсаалтыг тоогоор эрэмбэлэх:

thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)

Sort Descending – Буурахаар Эрэмбэлэх #

To sort descending, use the keyword argument reverse = True:

Буурахаар эрэмбэлэхийн тулд reverse = True түлхүүр үгийг ашиглана:

Example – Жишээ #

Sort the list descending:

Жагсаалтыг буурахаар эрэмбэлэх:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)

Example – Жишээ #

Sort the list descending:

Жагсаалтыг буурахаар эрэмбэлэх:

thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)

Customize Sort Function – Эрэмбэлэх Функцийг Тохируулах #

You can also customize your own function by using the keyword argument key = function.

Мөн өөрийн функцээ key = function түлхүүр үгийг ашиглан тохируулах боломжтой.

The function will return a number that will be used to sort the list (the lowest number first):

Функц нь жагсаалтыг эрэмбэлэхэд ашиглагдах тоог буцаах болно (хамгийн бага тоо эхэлж):

Example – Жишээ #

Sort the list based on how close the number is to 50:

Тоонуудыг 50-д хэр ойр байгаагаар нь жагсаалтыг эрэмбэлэх:

def myfunc(n):
  return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)

Case Insensitive Sort – Эрэмбэлхэд том жижиг үсэг хамаарагдахгүй #

By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters:

Өгөгдмөл байдлаар sort() арга нь бүх том үсгүүд жижиг үсгүүдээс өмнө эрэмбэлэгддэг:

Example – Жишээ #

Case sensitive sorting can give an unexpected result:

Том үсгээр эрэмбэлэх нь гэнэтийн үр дүнг өгч болно:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)

Luckily we can use built-in functions as key functions when sorting a list.

Аз болоход бид жагсаалтыг эрэмбэлэхдээ үүсгэсэн функцуудыг үндсэн функц болгон ашиглаж болно.

So if you want a case-insensitive sort function, use str.lower as a key function:

Хэрэв та кейс мэдрэмжгүй эрэмбэлэх функц хүсэж байгаа бол str.lower-ийг түлхүүр функц болгон ашиглана:

Example – Жишээ #

Perform a case-insensitive sort of the list:

Жагсаалтыг том үсгээр эрэмбэлэхгүй:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)

Reverse Order – Дарааллыг Буцаах #

What if you want to reverse the order of a list, regardless of the alphabet?

Жагсаалтын дарааллыг цагаан толгойн дарааллаар биш эсргээр нь буцаахыг хүсвэл яах вэ?

The reverse() method reverses the current sorting order of the elements.

reverse() арга нь элементүүдийн одоогийн эрэмбэлтийг эсрэг дарааллаар буцаана.

Example – Жишээ #

Reverse the order of the list items:

Жагсаалтын зүйлсийг эсрэг дарааллаар буцаах:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)

Python – Copy Lists – Python – Жагсаалтыг Хуулах #

Copy a List – Жагсаалтыг Хуулах #

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.

Жагсаалтыг list2 = list1 гэж бичих замаар хуулах боломжгүй, учир нь: list2 нь зөвхөн list1-ийг лавлах бөгөөд list1-д хийгдсэн өөрчлөлтүүд автоматаар list2-д бас хийгдэнэ.

There are ways to make a copy, one way is to use the built-in List method copy().

Жагсаалтыг хуулах аргууд бий, нэг арга нь List аргад байх copy()-г ашиглана.

Example – Жишээ #

Make a copy of a list with the copy() method:

copy() аргыг ашиглан жагсаалтыг хуулах:

thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().

Өөр нэг хуулах арга нь list() аргыг ашиглана.

Example – Жишээ #

Make a copy of a list with the list() method:

list() аргыг ашиглан жагсаалтыг хуулах:

thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

Python – Join Lists – Python – Жагсаалтуудыг Нийлүүлэх #

Join Two Lists – Хоёр Жагсаалтыг Нийлүүлэх #

There are several ways to join, or concatenate, two or more lists in Python.

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

One of the easiest ways are by using the + operator.

Хамгийн хялбар аргуудын нэг нь + операторыг ашиглах.

Example – Жишээ #

Join two list:

Хоёр жагсаалтыг нийлүүлэх:

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)

Another way to join two lists is by appending all the items from list2 into list1, one by one:

Өөр нэг арга нь list2-ийн бүх зүйлсийг нэг нэгээр нь list1-д нэмэх.

Example – Жишээ #

Append list2 into list1:

list2-ийг list1-д нэмэх:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
  list1.append(x)
print(list1))

Or you can use the extend() method, where the purpose is to add elements from one list to another list:

Эсвэл та extend() аргыг ашиглаж болно, энэ нь нэг жагсаалтаас нөгөө жагсаалт руу элементүүдийг нэмэх зорилготой.

Example – Жишээ #

Use the extend() method to add list2 at the end of list1:

extend() аргыг ашиглаж list2-ийг list1-ийн төгсгөлд нэмэх:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)

Python – List Methods – Python – Жагсаалтын Аргууд #

List Methods – Жагсаалтын Аргууд #

Python has a set of built-in methods that you can use on lists.

Python жагсаалтуудад ашиглаж болох багц аргууд.

Method

Арга

Description

Тайлбар

append()

Adds an element at the end of the list

Элементийг жагсаалтын төгсгөлд нэмнэ

clear()

Removes all the elements from the list

Жагсаалтын бүх элементүүдийг устгана

copy()

Returns a copy of the list

Жагсаалтын хуулбарыг буцаана

count()

Returns the number of elements with the specified value

Тодорхой утгатай элементүүдийн тоог буцаана

extend()

Add the elements of a list (or any iterable), to the end of the current list

Жагсаалтын элементүүдийг (эсвэл ямар нэгэн iterable) одоогийн жагсаалтын төгсгөлд нэмнэ

index()

Returns the index of the first element with the specified value

Тодорхой утгатай анхны элементийн индексийг буцаана

insert()

Adds an element at the specified position

Тодорхой байршилд элементийг нэмнэ

pop()

Removes the element at the specified position

Тодорхой байршлын элементийг устгана

remove()

Removes the item with the specified value

Тодорхой утгатай зүйлийг устгана

reverse()

Reverses the order of the list

Жагсаалтын дарааллыг буцаана

sort()

Sorts the list

Жагсаалтыг эрэмбэлнэ

Powered by BetterDocs

Leave a Reply