Агуулга

Python Sets – Python – Олонлогууд #

myset = {“apple”, “banana”, “cherry”}

Set – Олонлог #

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

Олонлог нь олон элементүүдийг нэг хувьсагчид хадгалахад ашиглагддаг.

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

Олонлог нь Python-д 4 төрлийн өгөгдлийн бүтцүүдийн нэг бөгөөд бусад 3 нь List, Tuple, Dictionary юм. Эдгээр нь бүгд өөрийн онцлог, хэрэглээтэй.

A set is a collection which is unorderedunchangeable*, and unindexed.

Олонлог нь дараалалгүй, өөрчлөгдөхгүй*, индексгүй цуглуулга юм.

* Note: Set items are unchangeable, but you can remove items and add new items.

* Тэмдэглэл: Олонлогийн элементүүдийг өөрчлөх боломжгүй боловч, элементүүдийг устгаж, шинэ элемент нэмэх боломжтой.

Sets are written with curly brackets.

Олонлогуудыг хээтэй хаалтан дотор бичнэ.

Example – Жишээ #

Create a Set:

Олонлог үүсгэх:

thisset = {"apple", "banana", "cherry"}
print(thisset)

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Тэмдэглэл: Олонлогууд дараалалгүй тул элементүүд ямар дарааллаар харагдах нь тодорхойгүй.

Set Items – Олонлогийн Элементүүд  #

Set items are unordered, unchangeable, and do not allow duplicate values.

Олонлогийн элементүүд дараалалгүй, өөрчлөгдөхгүй бөгөөд давхардах утгуудыг зөвшөөрдөггүй.

Unordered – Дараалалгүй #

Unordered means that the items in a set do not have a defined order.

Дараалалгүй гэдэг нь олонлогийн элементүүд тодорхой дарааллаар байхгүй гэсэн үг.

Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Олонлогийн элементүүдийг ашиглах бүрт өөр дарааллаар харагдаж болно, мөн индексээр эсвэл түлхүүрээр хандах боломжгүй.

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

Set items are unchangeable, meaning that we cannot change the items after the set has been created.

Олонлогийн элементүүдийг өөрчлөх боломжгүй, энэ нь олонлог үүсгэгдсэнээс хойш элементүүдийг өөрчлөх боломжгүй гэсэн үг.

Once a set is created, you cannot change its items, but you can remove items and add new items.

Олонлог үүсгэсний дараа элементүүдийг өөрчлөх боломжгүй, гэхдээ та элементүүдийг устгаж, шинэ элементүүдийг нэмж болно.

Duplicates Not Allowed – Давхардахыг Зөвшөөрөхгүй #

Sets cannot have two items with the same value.

Олонлогуудад нэг утгыг давхардуулах боломжгүй.

Example – Жишээ #

Duplicate values will be ignored:

Давхардасан утгуудыг тооцохгүй:

thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)

Note: The values True and 1 are considered the same value in sets, and are treated as duplicates:

Тэмдэглэл: Олонлогуудад True болон 1 утгууд ижил утга гэж тооцогддог бөгөөд давхардаж үзнэ:

Example – Жишээ #

True and 1 is considered the same value:

True болон 1 ижил утга гэж тооцогдоно:

thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset)

Note: The values False and 0 are considered the same value in sets, and are treated as duplicates:

Тэмдэглэл: Олонлогуудад False болон 0 утгууд ижил утга гэж тооцогддог бөгөөд давхардаж үзнэ:

Example – Жишээ #

False and 0 is considered the same value:

False болон 0 ижил утга гэж тооцогдоно:

thisset = {"apple", "banana", "cherry", False, True, 0}
print(thisset)

Get the Length of a Set – Олонлогийн Уртыг харах #

To determine how many items a set has, use the len() function.

Олонлогт хэдэн элемент байгааг тодорхойлоход len() функцийг ашиглана.

Example – Жишээ #

Get the number of items in a set:

Олонлогт хэдэн элемент байгааг харуулах:

thisset = {"apple", "banana", "cherry"}
print(len(thisset))

Set Items – Data Types – Олонлогийн Элементүүд – Өгөгдлийн Төрлүүд #

Set items can be of any data type:

Олонлогийн элементүүд ямар ч өгөгдлийн төрөлтэй байж болно:

Example – Жишээ #

String, int and boolean data types:

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

set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

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

Example – Жишээ #

A set with strings, integers and boolean values:

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

set1 = {"abc", 34, True, 40, "male"}

type() #

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

Python-ий хувьд, олонлогууд set өгөгдлийн төрөлтэй обьектууд гэж тодорхойлогдоно:

<class ‘set’>

Example – Жишээ #

What is the data type of a set?

Олонлог ямар өгөгдлийн төрөлтэй вэ?

myset = {"apple", "banana", "cherry"}
print(type(myset))

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

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

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

Example – Жишээ #

Using the set() constructor to make a set:

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

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

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

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

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

  • 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 items and add new items.

*Олонлогийн элементүүдийг өөрчлөх боломжгүй, гэхдээ элементүүдийг устгаж, шинэ элементүүдийг нэмж болно.

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

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

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 Set Items – Python – Олонлогийн Элементүүдэд Хандах #

Access Items – Элементүүдэд Хандах  #

You cannot access items in a set by referring to an index or a key.

Олонлогт байгаа элементүүдэд индекс эсвэл түлхүүр ашиглан хандах боломжгүй.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

Гэхдээ for давталтыг ашиглан олонлогийн элементүүдийг давтах эсвэл тодорхой утгат олонлог байгаа эсэхийг in түлхүүр үгээр шалгах боломжтой.

Example – Жишээ #

Loop through the set, and print the values:

Олонлогийг давтаж, утгуудыг хэвлэх:

thisset = {"apple", "banana", "cherry"}
for x in thisset:
  print(x)

Example – Жишээ #

Check if “banana” is present in the set:

“banana” олонлогт байгаа эсэхийг шалгах:

thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

Change Items – Элементүүдийг Өөрчлөх  #

Once a set is created, you cannot change its items, but you can add new items.

Олонлог үүсгэгдсэнээс хойш элементүүдийг өөрчлөх боломжгүй, гэхдээ шинэ элементүүдийг нэмж болно.

Python – Add Set Items – Python – Олонлогт Элементүүдийг Нэмэх #

Add Items – Элементүүдийг Нэмэх #

Once a set is created, you cannot change its items, but you can add new items.

Олонлог үүсгэгдсэнээс хойш элементүүдийг өөрчлөх боломжгүй, гэхдээ шинэ элементүүдийг нэмж болно.

To add one item to a set use the add() method.

Олонлогт нэг элемент нэмэхийн тулд add() аргамийг ашиглана.

Example – Жишээ #

Add an item to a set, using the add() method:

Олонлогт нэг элемент add() аргаар нэмэх:

thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

Add Sets – Олонлог Нэмэх #

To add items from another set into the current set, use the update() method.

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

Example – Жишээ #

Add elements from tropical into thisset:

tropical олонлогийн элементүүдийг thisset олонлогт нэмэх:

thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)

Add Any Iterable – Ямар нэгэн давталт нэмэх #

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).

update() аргын обьект нь олонлог байх албагүй, ямар нэгэн давталт обьект (tuple, list, dictionary гэх мэт) байж болно.

Example – Жишээ #

Add elements of a list to at set:

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

thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)

Python – Join Sets – Python – Олонлогуудыг Холбох #

 

Join Two Sets – Хоёр Олонлогийг Холбох  #

There are several ways to join two or more sets in Python.

Python-д хоёр болон түүнээс олон олонлогийг холбох хэд хэдэн арга байдаг.

You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:

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

Example – Жишээ #

The union() method returns a new set with all items from both sets:

union() аргыг ашиглан хоёр олонлогийг нэгтгэх:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

Example – Жишээ #

The update() method inserts the items in set2 into set1:

update() аргыг ашиглан set2-ийн элементүүдийг set1-д нэмэх:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

Note: Both union() and update() will exclude any duplicate items.

Тэмдэглэл: union() болон update() аль аль нь давхардсан элементүүдийг хасах болно.

Keep ONLY the Duplicates – Зөвхөн Давхардагч Элементүүдийг Үлдээх #

The intersection_update() method will keep only the items that are present in both sets.

intersection_update() арга нь зөвхөн хоёр олонлогийн аль алинд нь байгаа элементүүдийг үлдээх болно.

Example – Жишээ #

Keep the items that exist in both set x, and set y:

x болон y олонлогийн аль алинд нь байгаа элементүүдийг үлдээх:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)

The intersection() method will return a new set, that only contains the items that are present in both sets.

Example #

Return a set that contains the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)

Keep All, But NOT the Duplicates #

The symmetric_difference_update() method will keep only the elements that are NOT present in both sets.

Example #

Keep the items that are not present in both sets:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets.

Example #

Return a set that contains all items from both sets, except items that are present in both:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

Note: The values True and 1 are considered the same value in sets, and are treated as duplicates:

Example #

True and 1 is considered the same value:

x = {"apple", "banana", "cherry", True}
y = {"google", 1, "apple", 2}
z = x.symmetric_difference(y)
print(z)

Python – Remove Set Items #

Remove Item #

To remove an item in a set, use the remove(), or the discard() method.

Example #

Remove “banana” by using the remove() method:

thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

Example #

Remove “banana” by using the discard() method:

thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

Note: If the item to remove does not exist, discard() will NOT raise an error.

You can also use the pop() method to remove an item, but this method will remove a random item, so you cannot be sure what item that gets removed.

The return value of the pop() method is the removed item.

Example #

Remove a random item by using the pop() method:

thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

Note: Sets are unordered, so when using the pop() method, you do not know which item that gets removed.

Example #

The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

Example #

The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

Python – Loop Sets #

Loop Items #

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

Example #

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}
for x in thisset:
  print(x)

Python Set copy() method #

Example #

Copy the fruits set:

fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x)

Definition and Usage #

The copy() method copies the set.

Syntax #

set.copy()

Parameter Values #

No parameters

Python Set difference() Method #

Example #

Return a set that contains the items that only exist in set x, and not in set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)

Definition and Usage #

The difference() method returns a set that contains the difference between two sets.

Meaning: The returned set contains items that exist only in the first set, and not in both sets.

Syntax #

set.difference(set)

Parameter Values #

Parameter Description
set Required. The set to check for differences in

More Examples #

Example #

Reverse the first example. Return a set that contains the items that only exist in set y, and not in set x:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = y.difference(x)
print(z)

Python Set difference_update() Method #

Example #

Remove the items that exist in both sets:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x)

Definition and Usage #

The difference_update() method removes the items that exist in both sets.

The difference_update() method is different from the difference() method, because the difference() method returns a new set, without the unwanted items, and the difference_update() method removes the unwanted items from the original set.

Syntax #

set.difference_update(set)

Parameter Values #

Parameter Description
set Required. The set to check for differences in

is methods – Set Methods #

Python Set isdisjoint() Method #

Example #

Return True if no items in set x is present in set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)

Definition and Usage #

The isdisjoint() method returns True if none of the items are present in both sets, otherwise it returns False.


Syntax #

set.isdisjoint(set)

  #

Parameter Values #

Parameter Description
set Required. The set to search for equal items in

More Examples #

Example #

What if no items are present in both sets?

Return False if one or more items are present in both sets:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.isdisjoint(y)
print(z)

Python Set issubset() Method #

Example #

Return True if all items in set x are present in set y:

x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)

Definition and Usage #

The issubset() method returns True if all items in the set exists in the specified set, otherwise it returns False.


Syntax #

set.issubset(set)

#

Parameter Values #

Parameter Description
set Required. The set to search for equal items in

More Examples #

Example #

What if not all items are present in the specified set?

Return False if not all items in set x are present in set y:

x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b"}
z = x.issubset(y)
print(z)

Python Set issuperset() Method #

Example #

Return True if all items set y are present in set x:

x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)

Definition and Usage #

The issubset() method returns True if all items in the set exists in the specified set, otherwise it returns False.


Syntax #

set.issuperset(set)

#

Parameter Values #

Parameter Description
set Required. The set to search for equal items in

More Examples #

Example #

What if not all items are present in the specified set?

Return False if not all items in set y are present in set x:

x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)

Python – Set Methods #

Set Methods #

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

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others

Powered by BetterDocs

Leave a Reply