1591590419
See how the compiler and runtime use the and methods for initialization purposes
The JVM uses two distinctive methods to initialize object instances and classes.
In this quick article, we’re going to see how the compiler and runtime use the _ _and _ _methods for initialization purposes.
#java #jvm
1591590419
See how the compiler and runtime use the and methods for initialization purposes
The JVM uses two distinctive methods to initialize object instances and classes.
In this quick article, we’re going to see how the compiler and runtime use the _ _and _ _methods for initialization purposes.
#java #jvm
1621628640
Python has a set of magic methods that can be used to enrich data classes; they are special in the way they are invoked. These methods are also called “dunder methods” because they start and end with double underscores. Dunder methods allow developers to emulate built-in methods, and it’s also how operator overloading is implemented in Python. For example, when we add two integers together, 4 + 2
, and when we add two strings together, “machine” + “learning”
, the behaviour is different. The strings get concatenated while the integers are actually added together.
If you have ever created a class of your own, you already know one of the dunder methods, __init__()
. Although it’s often referred to as the constructor, it’s not the real constructor; the __new__()
method is the constructor. The superclass’s __new__()
, super().__new__(cls[, ...])
, method is invoked, which creates an instance of the class, which is then passed to the __init__()
along with other arguments. Why go through the ordeal of creating the __new__()
method? You don’t need to; the __new__()
method was created mainly to facilitate the creation of subclasses of immutable types (such as int, str, list) and metaclasses.
#developers corner #uncategorized #dunder methods #magic methods #operator overriding #python dunder methods #python magic methods
1662358320
В любом языке программирования нам нужно иметь дело с данными. Теперь одной из самых фундаментальных вещей, которые нам нужны для работы с данными, является эффективное хранение, управление и доступ к ним организованным образом, чтобы их можно было использовать всякий раз, когда это необходимо для наших целей. Структуры данных используются для удовлетворения всех наших потребностей.
Структуры данных являются фундаментальными строительными блоками языка программирования. Он направлен на обеспечение системного подхода для выполнения всех требований, упомянутых ранее в статье. Структуры данных в Python — это List, Tuple, Dictionary и Set . Они считаются неявными или встроенными структурами данных в Python . Мы можем использовать эти структуры данных и применять к ним многочисленные методы для управления, связывания, манипулирования и использования наших данных.
У нас также есть пользовательские структуры данных, определяемые пользователем, а именно Stack , Queue , Tree , Linked List и Graph . Они позволяют пользователям полностью контролировать их функциональность и использовать их для расширенных целей программирования. Однако в этой статье мы сосредоточимся на встроенных структурах данных.
Неявные структуры данных Python
Списки помогают нам хранить наши данные последовательно с несколькими типами данных. Они сопоставимы с массивами за исключением того, что они могут одновременно хранить разные типы данных, такие как строки и числа. Каждый элемент или элемент в списке имеет назначенный индекс. Поскольку Python использует индексацию на основе 0, первый элемент имеет индекс 0, и подсчет продолжается. Последний элемент списка начинается с -1, что можно использовать для доступа к элементам от последнего к первому. Чтобы создать список, мы должны написать элементы внутри квадратных скобок .
Одна из самых важных вещей, которые нужно помнить о списках , это то, что они изменяемы . Это просто означает, что мы можем изменить элемент в списке, обратившись к нему напрямую как часть оператора присваивания с помощью оператора индексации. Мы также можем выполнять операции в нашем списке, чтобы получить желаемый результат. Давайте рассмотрим код, чтобы лучше понять список и операции со списками.
1. Создание списка
#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)
Выход
['p', 'r', 'o', 'b', 'e']
2. Доступ к элементам из списка
#accessing the list
#accessing the first item of the list
my_list[0]
Выход
'p'
#accessing the third item of the list
my_list[2]
'o'
3. Добавление новых элементов в список
#adding item to the list
my_list + ['k']
Выход
['p', 'r', 'o', 'b', 'e', 'k']
4. Удаление элементов
#removing item from the list
#Method 1:
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# delete one item
del my_list[2]
print(my_list)
# delete multiple items
del my_list[1:5]
print(my_list)
Выход
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
print(my_list)
#Method 3:
#with pop function
print(my_list.pop(1))
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)
Выход
['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']
5. Список сортировки
#sorting of list in ascending order
my_list.sort()
print(my_list)
Выход
['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
my_list.sort(reverse=True)
print(my_list)
Выход
['y', 'r', 'm', 'l', 'k']
6. Нахождение длины списка
#finding the length of list
len(my_list)
Выход
5
Кортежи очень похожи на списки с той ключевой разницей, что кортеж является IMMUTABLE , в отличие от списка. Как только мы создаем кортеж или имеем кортеж, нам не разрешается изменять элементы внутри него. Однако если у нас есть элемент внутри кортежа, который сам является списком, только тогда мы можем получить доступ к этому списку или изменить его. Чтобы создать кортеж, мы должны написать элементы внутри круглых скобок . Как и со списками, у нас есть аналогичные методы, которые можно использовать с кортежами. Давайте рассмотрим некоторые фрагменты кода, чтобы понять, как использовать кортежи.
1. Создание кортежа
#creating of tuple
my_tuple = ("apple", "banana", "guava")
print(my_tuple)
Выход
('apple', 'banana', 'guava')
2. Доступ к элементам из кортежа
#accessing first element in tuple
my_tuple[1]
Выход
'banana'
3. Длина кортежа
#for finding the lenght of tuple
len(my_tuple)
Выход
3
4. Преобразование кортежа в список
#converting tuple into a list
my_tuple_list = list(my_tuple)
type(my_tuple_list)
Выход
list
5. Реверс кортежа
#Reversing a tuple
tuple(sorted(my_tuple, reverse=True))
Выход
('guava', 'banana', 'apple')
6. Сортировка кортежа
#sorting tuple in ascending order
tuple(sorted(my_tuple))
Выход
('apple', 'banana', 'guava')
7. Удаление элементов из кортежа
Для удаления элементов из кортежа мы сначала преобразовали кортеж в список, как мы сделали в одном из наших методов выше (пункт № 4), затем следовали тому же процессу списка и явно удалили весь кортеж, просто используя del заявление .
Словарь — это коллекция, которая просто означает, что она используется для хранения значения с некоторым ключом и извлечения значения по данному ключу. Мы можем думать об этом как о наборе пар ключ: значение, и каждый ключ в словаре должен быть уникальным , чтобы мы могли получить соответствующий доступ к соответствующим значениям .
Словарь обозначается фигурными скобками { } , содержащими пары ключ: значение. Каждая из пар в словаре разделена запятой. Элементы в словаре неупорядочены , последовательность не имеет значения, пока мы обращаемся к ним или сохраняем их.
Они ИЗМЕНЯЕМЫ , что означает, что мы можем добавлять, удалять или обновлять элементы в словаре. Вот несколько примеров кода, чтобы лучше понять словарь в Python.
Важно отметить, что мы не можем использовать изменяемый объект в качестве ключа в словаре. Таким образом, список не допускается в качестве ключа в словаре.
1. Создание словаря
#creating a dictionary
my_dict = {
1:'Delhi',
2:'Patna',
3:'Bangalore'
}
print(my_dict)
Выход
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
Здесь целые числа — это ключи словаря, а название города, связанное с целыми числами, — это значения словаря.
2. Доступ к элементам из словаря
#access an item
print(my_dict[1])
Выход
'Delhi'
3. Длина словаря
#length of the dictionary
len(my_dict)
Выход
3
4. Сортировка словаря
#sorting based on the key
Print(sorted(my_dict.items()))
#sorting based on the values of dictionary
print(sorted(my_dict.values()))
Выход
[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
['Bangalore', 'Delhi', 'Patna']
5. Добавление элементов в Словарь
#adding a new item in dictionary
my_dict[4] = 'Lucknow'
print(my_dict)
Выход
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}
6. Удаление элементов из словаря
#for deleting an item from dict using the specific key
my_dict.pop(4)
print(my_dict)
#for deleting last item from the list
my_dict.popitem()
#for clearing the dictionary
my_dict.clear()
print(my_dict)
Выход
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}
Set — это еще один тип данных в python, представляющий собой неупорядоченную коллекцию без повторяющихся элементов. Общие варианты использования набора — удаление повторяющихся значений и проверка принадлежности. Фигурные скобки или set()функция могут использоваться для создания наборов. Следует иметь в виду, что при создании пустого набора мы должны использовать set(), и . Последний создает пустой словарь. not { }
Вот несколько примеров кода, чтобы лучше понять наборы в python.
1. Создание набора
#creating set
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)
Выход
{'apple', 'strawberry', 'mango'}
2. Доступ к элементам из набора
#to test for an element inside the set
"apple" in my_set
Выход
True
3. Длина набора
print(len(my_set))
Выход
3
4. Сортировка набора
print(sorted(my_set))
Выход
['apple', 'mango', 'strawberry']
5. Добавление элементов в Set
my_set.add("guava")
print(my_set)
Выход
{'apple', 'guava', 'mango', 'strawberry'}
6. Удаление элементов из Set
my_set.remove("mango")
print(my_set)
Выход
{'apple', 'guava', 'strawberry'}
В этой статье мы рассмотрели наиболее часто используемые структуры данных в Python, а также рассмотрели различные связанные с ними методы.
Ссылка: https://www.askpython.com/python/data
#python #datastructures
1662480600
In any programming language, we need to deal with data. Now, one of the most fundamental things that we need to work with the data is to store, manage, and access it efficiently in an organized way so it can be utilized whenever required for our purposes. Data Structures are used to take care of all our needs.
Data Structures are fundamental building blocks of a programming language. It aims to provide a systematic approach to fulfill all the requirements mentioned previously in the article. The data structures in Python are List, Tuple, Dictionary, and Set. They are regarded as implicit or built-in Data Structures in Python. We can use these data structures and apply numerous methods to them to manage, relate, manipulate and utilize our data.
We also have custom Data Structures that are user-defined namely Stack, Queue, Tree, Linked List, and Graph. They allow users to have full control over their functionality and use them for advanced programming purposes. However, we will be focussing on the built-in Data Structures for this article.
Implicit Data Structures Python
Lists help us to store our data sequentially with multiple data types. They are comparable to arrays with the exception that they can store different data types like strings and numbers at the same time. Every item or element in a list has an assigned index. Since Python uses 0-based indexing, the first element has an index of 0 and the counting goes on. The last element of a list starts with -1 which can be used to access the elements from the last to the first. To create a list we have to write the items inside the square brackets.
One of the most important things to remember about lists is that they are Mutable. This simply means that we can change an element in a list by accessing it directly as part of the assignment statement using the indexing operator. We can also perform operations on our list to get desired output. Let’s go through the code to gain a better understanding of list and list operations.
1. Creating a List
#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)
Output
['p', 'r', 'o', 'b', 'e']
2. Accessing items from the List
#accessing the list
#accessing the first item of the list
my_list[0]
Output
'p'
#accessing the third item of the list
my_list[2]
'o'
3. Adding new items to the list
#adding item to the list
my_list + ['k']
Output
['p', 'r', 'o', 'b', 'e', 'k']
4. Removing Items
#removing item from the list
#Method 1:
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# delete one item
del my_list[2]
print(my_list)
# delete multiple items
del my_list[1:5]
print(my_list)
Output
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
print(my_list)
#Method 3:
#with pop function
print(my_list.pop(1))
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)
Output
['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']
5. Sorting List
#sorting of list in ascending order
my_list.sort()
print(my_list)
Output
['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
my_list.sort(reverse=True)
print(my_list)
Output
['y', 'r', 'm', 'l', 'k']
6. Finding the length of a List
#finding the length of list
len(my_list)
Output
5
Tuples are very similar to lists with a key difference that a tuple is IMMUTABLE, unlike a list. Once we create a tuple or have a tuple, we are not allowed to change the elements inside it. However, if we have an element inside a tuple, which is a list itself, only then we can access or change within that list. To create a tuple, we have to write the items inside the parenthesis. Like the lists, we have similar methods which can be used with tuples. Let’s go through some code snippets to understand using tuples.
1. Creating a Tuple
#creating of tuple
my_tuple = ("apple", "banana", "guava")
print(my_tuple)
Output
('apple', 'banana', 'guava')
2. Accessing items from a Tuple
#accessing first element in tuple
my_tuple[1]
Output
'banana'
3. Length of a Tuple
#for finding the lenght of tuple
len(my_tuple)
Output
3
4. Converting a Tuple to List
#converting tuple into a list
my_tuple_list = list(my_tuple)
type(my_tuple_list)
Output
list
5. Reversing a Tuple
#Reversing a tuple
tuple(sorted(my_tuple, reverse=True))
Output
('guava', 'banana', 'apple')
6. Sorting a Tuple
#sorting tuple in ascending order
tuple(sorted(my_tuple))
Output
('apple', 'banana', 'guava')
7. Removing elements from Tuple
For removing elements from the tuple, we first converted the tuple into a list as we did in one of our methods above( Point No. 4) then followed the same process of the list, and explicitly removed an entire tuple, just using the del statement.
Dictionary is a collection which simply means that it is used to store a value with some key and extract the value given the key. We can think of it as a set of key: value pairs and every key in a dictionary is supposed to be unique so that we can access the corresponding values accordingly.
A dictionary is denoted by the use of curly braces { } containing the key: value pairs. Each of the pairs in a dictionary is comma separated. The elements in a dictionary are un-ordered the sequence does not matter while we are accessing or storing them.
They are MUTABLE which means that we can add, delete or update elements in a dictionary. Here are some code examples to get a better understanding of a dictionary in python.
An important point to note is that we can’t use a mutable object as a key in the dictionary. So, a list is not allowed as a key in the dictionary.
1. Creating a Dictionary
#creating a dictionary
my_dict = {
1:'Delhi',
2:'Patna',
3:'Bangalore'
}
print(my_dict)
Output
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
Here, integers are the keys of the dictionary and the city name associated with integers are the values of the dictionary.
2. Accessing items from a Dictionary
#access an item
print(my_dict[1])
Output
'Delhi'
3. Length of a Dictionary
#length of the dictionary
len(my_dict)
Output
3
4. Sorting a Dictionary
#sorting based on the key
Print(sorted(my_dict.items()))
#sorting based on the values of dictionary
print(sorted(my_dict.values()))
Output
[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
['Bangalore', 'Delhi', 'Patna']
5. Adding elements in Dictionary
#adding a new item in dictionary
my_dict[4] = 'Lucknow'
print(my_dict)
Output
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}
6. Removing elements from Dictionary
#for deleting an item from dict using the specific key
my_dict.pop(4)
print(my_dict)
#for deleting last item from the list
my_dict.popitem()
#for clearing the dictionary
my_dict.clear()
print(my_dict)
Output
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}
Set is another data type in python which is an unordered collection with no duplicate elements. Common use cases for a set are to remove duplicate values and to perform membership testing. Curly braces or the set()
function can be used to create sets. One thing to keep in mind is that while creating an empty set, we have to use set()
, and not { }
. The latter creates an empty dictionary.
Here are some code examples to get a better understanding of sets in python.
1. Creating a Set
#creating set
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)
Output
{'apple', 'strawberry', 'mango'}
2. Accessing items from a Set
#to test for an element inside the set
"apple" in my_set
Output
True
3. Length of a Set
print(len(my_set))
Output
3
4. Sorting a Set
print(sorted(my_set))
Output
['apple', 'mango', 'strawberry']
5. Adding elements in Set
my_set.add("guava")
print(my_set)
Output
{'apple', 'guava', 'mango', 'strawberry'}
6. Removing elements from Set
my_set.remove("mango")
print(my_set)
Output
{'apple', 'guava', 'strawberry'}
In this article, we went through the most commonly used data structures in python and also saw various methods associated with them.
Link: https://www.askpython.com/python/data
#python #datastructures
1662380058
Trong bất kỳ ngôn ngữ lập trình nào, chúng ta cần xử lý dữ liệu. Bây giờ, một trong những điều cơ bản nhất mà chúng ta cần làm việc với dữ liệu là lưu trữ, quản lý và truy cập nó một cách hiệu quả theo cách có tổ chức để nó có thể được sử dụng bất cứ khi nào được yêu cầu cho các mục đích của chúng ta. Cấu trúc dữ liệu được sử dụng để đáp ứng mọi nhu cầu của chúng tôi.
Cấu trúc dữ liệu là các khối xây dựng cơ bản của một ngôn ngữ lập trình. Nó nhằm mục đích cung cấp một cách tiếp cận có hệ thống để đáp ứng tất cả các yêu cầu được đề cập trước đó trong bài báo. Các cấu trúc dữ liệu trong Python là Danh sách, Tuple, Từ điển và Tập hợp . Chúng được coi là Cấu trúc dữ liệu ngầm định hoặc được tích hợp sẵn trong Python . Chúng tôi có thể sử dụng các cấu trúc dữ liệu này và áp dụng nhiều phương pháp cho chúng để quản lý, liên quan, thao tác và sử dụng dữ liệu của chúng tôi.
Chúng tôi cũng có các Cấu trúc Dữ liệu tùy chỉnh do người dùng xác định cụ thể là Ngăn xếp , Hàng đợi , Cây , Danh sách được Liên kết và Đồ thị . Chúng cho phép người dùng có toàn quyền kiểm soát chức năng của chúng và sử dụng chúng cho các mục đích lập trình nâng cao. Tuy nhiên, chúng tôi sẽ tập trung vào Cấu trúc dữ liệu tích hợp cho bài viết này.
Python cấu trúc dữ liệu ngầm
Danh sách giúp chúng tôi lưu trữ dữ liệu của mình một cách tuần tự với nhiều kiểu dữ liệu. Chúng có thể so sánh với mảng với ngoại lệ là chúng có thể lưu trữ các kiểu dữ liệu khác nhau như chuỗi và số cùng một lúc. Mỗi mục hoặc phần tử trong danh sách đều có một chỉ mục được chỉ định. Vì Python sử dụng lập chỉ mục dựa trên 0 , phần tử đầu tiên có chỉ mục là 0 và việc đếm vẫn tiếp tục. Phần tử cuối cùng của danh sách bắt đầu bằng -1 có thể được sử dụng để truy cập các phần tử từ cuối cùng đến đầu tiên. Để tạo một danh sách, chúng ta phải viết các mục bên trong dấu ngoặc vuông .
Một trong những điều quan trọng nhất cần nhớ về danh sách là chúng có thể thay đổi . Điều này đơn giản có nghĩa là chúng ta có thể thay đổi một phần tử trong danh sách bằng cách truy cập trực tiếp vào nó như một phần của câu lệnh gán bằng cách sử dụng toán tử lập chỉ mục. Chúng tôi cũng có thể thực hiện các thao tác trên danh sách của mình để có được đầu ra mong muốn. Chúng ta hãy đi qua đoạn mã để hiểu rõ hơn về danh sách và các hoạt động của danh sách.
1. Tạo danh sách
#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)
Đầu ra
['p', 'r', 'o', 'b', 'e']
2. Truy cập các mục từ Danh sách
#accessing the list
#accessing the first item of the list
my_list[0]
Đầu ra
'p'
#accessing the third item of the list
my_list[2]
'o'
3. Thêm các mục mới vào danh sách
#adding item to the list
my_list + ['k']
Đầu ra
['p', 'r', 'o', 'b', 'e', 'k']
4. Loại bỏ các mục
#removing item from the list
#Method 1:
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# delete one item
del my_list[2]
print(my_list)
# delete multiple items
del my_list[1:5]
print(my_list)
Đầu ra
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
print(my_list)
#Method 3:
#with pop function
print(my_list.pop(1))
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)
Đầu ra
['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']
5. Danh sách sắp xếp
#sorting of list in ascending order
my_list.sort()
print(my_list)
Đầu ra
['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
my_list.sort(reverse=True)
print(my_list)
Đầu ra
['y', 'r', 'm', 'l', 'k']
6. Tìm độ dài của một danh sách
#finding the length of list
len(my_list)
Đầu ra
5
Tuple rất giống với danh sách với một điểm khác biệt chính là tuple là NGAY LẬP TỨC , không giống như một danh sách. Khi chúng tôi tạo một bộ hoặc có một bộ, chúng tôi không được phép thay đổi các phần tử bên trong nó. Tuy nhiên, nếu chúng ta có một phần tử bên trong một tuple, chính là một danh sách, thì chỉ khi đó chúng ta mới có thể truy cập hoặc thay đổi trong danh sách đó. Để tạo một bộ giá trị, chúng ta phải viết các mục bên trong dấu ngoặc đơn . Giống như danh sách, chúng tôi có các phương pháp tương tự có thể được sử dụng với các bộ giá trị. Hãy xem qua một số đoạn mã để hiểu cách sử dụng bộ giá trị.
1. Tạo Tuple
#creating of tuple
my_tuple = ("apple", "banana", "guava")
print(my_tuple)
Đầu ra
('apple', 'banana', 'guava')
2. Truy cập các mục từ Tuple
#accessing first element in tuple
my_tuple[1]
Đầu ra
'banana'
3. Chiều dài của một Tuple
#for finding the lenght of tuple
len(my_tuple)
Đầu ra
3
4. Chuyển đổi Tuple sang danh sách
#converting tuple into a list
my_tuple_list = list(my_tuple)
type(my_tuple_list)
Đầu ra
list
5. Đảo ngược Tuple
#Reversing a tuple
tuple(sorted(my_tuple, reverse=True))
Đầu ra
('guava', 'banana', 'apple')
6. Sắp xếp một Tuple
#sorting tuple in ascending order
tuple(sorted(my_tuple))
Đầu ra
('apple', 'banana', 'guava')
7. Xóa các phần tử khỏi Tuple
Để xóa các phần tử khỏi bộ tuple, trước tiên chúng tôi chuyển đổi bộ tuple thành một danh sách như chúng tôi đã làm trong một trong các phương pháp của chúng tôi ở trên (Điểm số 4), sau đó thực hiện theo cùng một quy trình của danh sách và loại bỏ rõ ràng toàn bộ bộ tuple, chỉ bằng cách sử dụng del tuyên bố .
Từ điển là một bộ sưu tập có nghĩa đơn giản là nó được sử dụng để lưu trữ một giá trị với một số khóa và trích xuất giá trị được cung cấp cho khóa. Chúng ta có thể coi nó như một tập hợp các cặp khóa: giá trị và mọi khóa trong từ điển được coi là duy nhất để chúng ta có thể truy cập các giá trị tương ứng tương ứng .
Một từ điển được biểu thị bằng cách sử dụng dấu ngoặc nhọn {} chứa các cặp key: value. Mỗi cặp trong từ điển được phân tách bằng dấu phẩy. Các phần tử trong từ điển không được sắp xếp theo thứ tự, trình tự không quan trọng khi chúng ta đang truy cập hoặc lưu trữ chúng.
Chúng MUTABLE có nghĩa là chúng ta có thể thêm, xóa hoặc cập nhật các phần tử trong từ điển. Dưới đây là một số ví dụ về mã để hiểu rõ hơn về từ điển trong python.
Một điểm quan trọng cần lưu ý là chúng ta không thể sử dụng một đối tượng có thể thay đổi làm khóa trong từ điển. Vì vậy, danh sách không được phép làm khóa trong từ điển.
1. Tạo từ điển
#creating a dictionary
my_dict = {
1:'Delhi',
2:'Patna',
3:'Bangalore'
}
print(my_dict)
Đầu ra
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
Ở đây, số nguyên là khóa của từ điển và tên thành phố được kết hợp với số nguyên là giá trị của từ điển.
2. Truy cập các mục từ Từ điển
#access an item
print(my_dict[1])
Đầu ra
'Delhi'
3. Độ dài của từ điển
#length of the dictionary
len(my_dict)
Đầu ra
3
4. Sắp xếp từ điển
#sorting based on the key
Print(sorted(my_dict.items()))
#sorting based on the values of dictionary
print(sorted(my_dict.values()))
Đầu ra
[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
['Bangalore', 'Delhi', 'Patna']
5. Thêm các phần tử trong Từ điển
#adding a new item in dictionary
my_dict[4] = 'Lucknow'
print(my_dict)
Đầu ra
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}
6. Xóa các phần tử khỏi Từ điển
#for deleting an item from dict using the specific key
my_dict.pop(4)
print(my_dict)
#for deleting last item from the list
my_dict.popitem()
#for clearing the dictionary
my_dict.clear()
print(my_dict)
Đầu ra
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}
Set là một kiểu dữ liệu khác trong python là một tập hợp không có thứ tự không có phần tử trùng lặp. Các trường hợp sử dụng phổ biến cho một tập hợp là loại bỏ các giá trị trùng lặp và thực hiện kiểm tra tư cách thành viên. Các dấu ngoặc nhọn hoặc set()hàm có thể được sử dụng để tạo bộ. Một điều cần lưu ý là trong khi tạo một tập hợp trống, chúng ta phải sử set()dụng và . Sau đó tạo ra một từ điển trống. not { }
Dưới đây là một số ví dụ mã để hiểu rõ hơn về các bộ trong python.
1. Tạo một Tập hợp
#creating set
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)
Đầu ra
{'apple', 'strawberry', 'mango'}
2. Truy cập các mục từ một Bộ
#to test for an element inside the set
"apple" in my_set
Đầu ra
True
3. Chiều dài của một bộ
print(len(my_set))
Đầu ra
3
4. Sắp xếp một tập hợp
print(sorted(my_set))
Đầu ra
['apple', 'mango', 'strawberry']
5. Thêm các phần tử trong Set
my_set.add("guava")
print(my_set)
Đầu ra
{'apple', 'guava', 'mango', 'strawberry'}
6. Xóa các phần tử khỏi Set
my_set.remove("mango")
print(my_set)
Đầu ra
{'apple', 'guava', 'strawberry'}
Trong bài viết này, chúng ta đã xem qua các cấu trúc dữ liệu được sử dụng phổ biến nhất trong python và cũng đã xem các phương thức khác nhau được liên kết với chúng.
Liên kết: https://www.askpython.com/python/data
#python #datastructures