python中定義數據結構
You have multiples algorithms, the steps of which require fetching the smallest value in a collection at any given point of time. Values are assigned to variables but are constantly modified, making it impossible for you to remember all the changes. One way to work through this problem is to store this collection in an unsorted array and then scan this collection every time, to find the required value. But considering the collection has N elements, this would lead to an increase in the required amount of time proportional to N.
您有多種算法,其步驟要求在任何給定時間點獲取集合中的最小值。 值已分配給變量,但會不斷修改,從而使您無法記住所有更改。 解決此問題的一種方法是將該集合存儲在未排序的數組中,然后每次掃描該集合以查找所需的值。 但是考慮到集合中有N個元素,這將導致與N成正比的所需時間增加。
Data structures to the rescue! Let us invent a common operation that ‘finds the minimum value from a set of elements.’ Here, the data structure is the common operation that all these algorithms will make use of to find the minimum element much faster.
數據結構搶救! 讓我們發明一個通用的操作,“從一組元素中找到最小值”。 在這里,數據結構是所有這些算法將用來更快地找到最小元素的常用操作。
There is no one single way of looking up data. Hence, when using an algorithm, make sure to understand the kind of data structures used by it and the operations they are a part of. The main purpose of a data structure is to speed up operations. In the above example, when I talk about an unsorted array, that too is a data structure. If the algorithm you are working with doesn’t care about a quicker result, you could continue using the array to get results.
沒有一種查找數據的單一方法。 因此,在使用算法時,請確保了解它所使用的數據結構的類型以及它們所包含的操作。 數據結構的主要目的是加快操作速度。 在上面的示例中,當我談論一個未排序的數組時,它也是一個數據結構。 如果您使用的算法不關心更快的結果,則可以繼續使用數組來獲取結果。
In case a data structure is what your algorithm requires, time must be spent on designing and maintaining one so that it becomes easier to query and update the structure.
如果您的算法需要一種數據結構,則必須花時間設計和維護一個數據結構,以便查詢和更新該結構變得更加容易。
Python中的數據結構 (Data Structures in Python)
Data structures provide us with a specific and way of storing and organizing data such that they can be easily accessed and worked with efficiently. In this article, you will learn about the various Python data structures and how they are implemented.
數據結構為我們提供了一種特定的方式來存儲和組織數據,以便可以輕松地訪問和有效地使用它們。 在本文中,您將學習各種Python數據結構及其實現方式。
A link to my GitHub repository to access the Jupyter notebook used for this demonstration:
指向我的GitHub存儲庫的鏈接,以訪問用于此演示的Jupyter筆記本:
Broadly speaking, data structures can be classified into two types — primitive and non-primitive. The former is the basic way of representing data which contain simple values. The latter is a more advanced and a complex way off representing data that contain a collection of values in various formats.
廣義上講,數據結構可以分為兩種類型:原始類型和非原始類型。 前者是表示包含簡單值的數據的基本方法。 后者是一種更高級,更復雜的方式,用于表示包含各種格式的值的集合的數據。
Non primitive data structures can further be categorized into built-in and user defined structures. Python offers implicit support for built in structures that include List, Tuple, Set and Dictionary. Users can also create their own data structures (like Stack, Tree, Queue, etc.) enabling them to have a full control over their functionality.
非原始數據結構可以進一步分為內置結構和用戶定義結構。 Python為內置結構(包括List,Tuple,Set和Dictionary)提供了隱式支持。 用戶還可以創建自己的數據結構(如堆棧,樹,隊列等),使他們能夠完全控制其功能。
清單 (LIST)
A list is a mutable sequence that can hold both homogeneous and heterogeneous data, in a sequential manner. An address is assigned to every element of the list, called an Index. The elements within a list are comma-separated and enclosed within square brackets.
列表是一個可變序列,可以按順序存儲同質和異質數據。 將地址分配給列表的每個元素,稱為索引。 列表中的元素以逗號分隔,并括在方括號內。
You can add, remove, or change elements from the list without changing its identity. Following are some of the functions used commonly while working with lists:
您可以在列表中添加,刪除或更改元素,而無需更改其標識。 以下是使用列表時常用的一些功能:

Creating a list:
創建列表:
initial_list = [1,2,3,4]
print(initial_list)
Lists can contain different types of variable, even in the same list.
列表可以包含不同類型的變量,即使在同一列表中也是如此。
my_list = ['R', 'Python', 'Julia', 1,2,3]
print(my_list)
Adding an element to a list:
將元素添加到列表中:
my_list = ['R', 'Python', 'Julia']
my_list.append(['C','Ruby'])
print(my_list)my_list.extend(['Java', 'HTML'])
print(my_list)my_list.insert(2, 'JavaScript')
print(my_list)
The outputs vary while using different functions like insert, extend and append with a list.
使用不同的功能(如插入,擴展和追加列表)時,輸出會有所不同。
· The insert function adds an element at the position/index specified.
·insert函數在指定的位置/索引處添加元素。
· The append function will add all elements specified, as a single element.
·append函數會將指定的所有元素添加為單個元素。
· The extend function will add elements on a one-by-one basis.
·擴展功能將在一對一的基礎上添加元素。
Accessing elements:
訪問元素:
Lists can be indexed using square brackets to retrieve the element stored in a position. Indexing in lists returns the entire item at that position whereas in strings, the character at that position is returned.
列表可以使用方括號索引,以檢索存儲在位置中的元素。 在列表中建立索引將返回該位置處的整個項目,而在字符串中,將返回該位置處的字符。

Deleting elements from a list:
從列表中刪除元素:
Once again, notice the outputs while using different functions like pop, delete and remove with the list. Remove is used when you want to remove element by specifying its value. We use del to remove an element by index, pop() to remove it by index if you need the returned value.
再一次,在使用彈出,刪除和刪除等不同功能時注意輸出。 如果要通過指定元素的值來刪除元素,則使用Remove。 如果需要返回的值,我們使用del刪除索引元素,pop()刪除索引元素。

Slicing a List:
切片列表:
While indexing is limited to accessing a single element, slicing accesses a sequence of data from a list.
雖然索引僅限于訪問單個元素,但切片訪問列表中的數據序列。
Slicing is done by defining the index values of the first element and the last element from the parent list that is required in the sliced list. It is written as [ a : b ] where a, b are the index values from the parent list. If a or b is not defined, then the index value is considered to be the first value for a if a is not defined and the last value for b when b is not defined.
通過定義切片列表中所需的父列表的第一個元素和最后一個元素的索引值來完成切片。 它寫為[a:b],其中a,b是父列表的索引值。 如果未定義a或b,則在未定義a時將索引值視為a的第一個值,而在未定義b時將索引值視為b的最后一個值。

Sort function:
排序功能:
# print the sorted list but not change the original onenumero = [1,12,4,25,19,8,29,6]
print(sorted(numero))
numero.sort(reverse=True)
print(numero)
Max, Min and ASCII value:
最大值,最小值和ASCII值:
· In a list with elements as string, max( ) and min( ) is applicable. max( ) would return a string element whose ASCII value is the highest and the lowest when min( ) is used.
·在以字符串為元素的列表中, max()和min()適用。 當使用min()時, max()將返回其ASCII值最高和最低的字符串元素。
· Only the first index of each element is considered each time and if their value is the same then the second index is considered and so on and so forth.
·每次只考慮每個元素的第一個索引,如果它們的值相同,則考慮第二個索引,依此類推。
new_list = ['apple','orange','banana','kiwi','melon']
print(max(new_list))
print(min(new_list))
And what happens in case numbers are declared as strings?
如果數字被聲明為字符串,會發生什么?
new_list1 =['3','45','22','56','11']
print(max(new_list1))
print(min(new_list1))
Even if the numbers are declared in a string the first index of each element is considered and the maximum and minimum values are returned accordingly.
即使數字在字符串中聲明,也要考慮每個元素的第一個索引,并相應地返回最大值和最小值。
You can also find the maximum and minimum values based on the length of a string.
您還可以根據字符串的長度找到最大值和最小值。
Copying & working on a list:
復制并處理列表:

Although no operation has been performed on the copied list, the values for it have also been changed. This is because you have assigned the same memory space of new_list to new_list_2.
盡管未對復制的列表執行任何操作,但其值也已更改。 這是因為您已將new_list的相同存儲空間分配給new_list_2。
How do we fix this?
我們該如何解決?
If you recall, in slicing we had seen that parent list [a:b] returns a list from parent list with start index a and end index b and if a and b is not mentioned then by default it considers the first and last element. We use the same concept here.
如果您還記得的話,在切片時,我們已經看到父列表[a:b]從父列表返回了一個列表,其起始索引為a,終止索引為b,如果未提及a和b,則默認情況下它將考慮第一個和最后一個元素。 我們在這里使用相同的概念。

管 (TUPLE)
Tuples are used to hold together multiple objects. Unlike lists, tuples are both immutable and specified within parentheses instead of square brackets. The values within a tuple cannot be overridden, that is, they cannot be changed, deleted, or reassigned. Tuples can hold both homogeneous and heterogeneous data.
元組用于將多個對象保持在一起。 與列表不同,元組是不可變的,并且在括號而不是方括號中指定。 元組中的值不能被覆蓋,也就是說,不能更改,刪除或重新分配它們。 元組可以同時存儲同質和異質數據。
Creating and accessing elements from a tuple:
從元組創建和訪問元素:

Appending a tuple:
附加一個元組:
tuple_1 = (1,2,3,4,5)
tuple_1 = tuple_1 + (6,7,8,9,10)
print(tuple_1)
Tuples are immutable.
元組是不可變的。
Divmod function:
Divmod函數:
Think of tuples as something which has to be True for a particular something and cannot be True for no other values. For better understanding, let’s use the divmod() function.
將元組視為對于特定事物必須為True且對于其他任何值都不能為True的事物。 為了更好地理解,讓我們使用divmod()函數。
xyz = divmod(10,3)
print(xyz)
print(type(xyz))
Here the quotient has to be 3 and the remainder has to be 1. These values cannot be changed whatsoever when 10 is divided by 3. Hence divmod returns these values in a tuple.
在這里,商必須為3,余數必須為1。將10除以3時,這些值都不能更改。因此divmod以元組形式返回這些值。
Built-In Tuple functions:
內置元組功能:
Count and Index are used with tuples as they are with lists.
計數和索引與元組一起使用,就像與列表一樣。
example = ("Mumbai","Chennai","Delhi","Kolkatta","Mumbai","Bangalore")
print(example.count("Mumbai"))print(example.index("Delhi"))
字典 (DICTIONARY)
If you are looking to implement something like a telephone book, a dictionary is what you need. Dictionaries basically store ‘key-value’ pairs. In a phone directory, you’ll have Phone and Name as keys and the various names and numbers assigned are the values. The ‘key’ identifies an item and the ‘value’ stores the item’s value. The ‘key-value’ pairs are separated by commas and the values are separated from the keys using a colon ‘:’ character.
如果您想實現電話簿之類的東西,則需要詞典。 字典基本上存儲“鍵值”對。 在電話目錄中,您將具有“電話”和“名稱”作為鍵,并且分配的各種名稱和數字是值。 “鍵”標識一個項目,“值”存儲該項目的值。 “鍵值”對用逗號分隔,并且值之間用冒號“:”字符與鍵分開。
You can add, remove, or change existing key-value pairs in a dictionary. Below mentioned are some of the common functions performed using a dictionary.
您可以在字典中添加,刪除或更改現有的鍵值對。 下面提到的是使用字典執行的一些常用功能。

Creating a dictionary:
創建字典:
new_dict = {} # empty dictionary
print(new_dict)
new_dict = {'Jyotika':1, 'Manu':2, 'Geeta':3, 'Manish':4}
print(new_dict)
Adding or changing a key-value pair:
添加或更改鍵值對:

Deleting key-value pairs:
刪除鍵值對:
· Use the pop() function to delete values, which returns the value that has been deleted.
·使用pop()函數刪除值,該值返回已刪除的值。
· To retrieve the key-value pair, you use the popitem() function which returns a tuple of the key and value.
·要檢索鍵值對,請使用popitem()函數,該鍵返回鍵和值的元組。
· To clear the entire dictionary, you use the clear() function.
·要清除整個詞典,請使用clear()函數。
new_dict_2 = new_dict.pop('Manu')
print(new_dict_2)
new_dict_3 = new_dict.popitem()
print(new_dict_3)
Values() and keys() functions:
Values()和keys()函數:
· values( ) function returns a list with all the assigned values in the dictionary.
·values()函數返回一個列表,其中包含字典中所有已分配的值。
· keys( ) function returns all the index or the keys to which contains the values that it was assigned to.
·keys()函數返回包含已為其分配值的所有索引或鍵。
print(new_dict.values())
print(type(new_dict.values()))
print(new_dict.keys())
print(type(new_dict.keys()))
集合 (SETS)
Sets are an unordered collection of unique elements. Sets are mutable but can hold only unique values in the dataset. Set operations are similar to the ones used in arithmetic.
集是唯一元素的無序集合。 集是可變的,但只能在數據集中保留唯一值。 設置操作類似于算術中使用的操作。
new_set = {1,2,3,3,3,4,5,5}
print(new_set)
new_set.add(8)
print(new_set)
Other operations on sets:
機上的其他操作:
.union() — combines data in both sets
.union() - 合并兩組數據
.intersection() — outputs data common to both sets
.intersection() —輸出兩組通用的數據
.difference() — deletes the data present in both and outputs data present only in the set passed.
.difference() —刪除兩個目錄中都存在的數據,并僅輸出所傳遞的集合中存在的數據。
.symmetricdifference() — deletes the data present in both and outputs the data which is remaining in both sets.
.symmetricdifference() —刪除兩個組中都存在的數據,并輸出兩個組中剩余的數據。

用戶定義的數據結構的簡要概述 (A brief overview of user-defined data structures)
- Stack: Based on the principles of FILO (first in last out) and LIFO (last in first out), stacks are linear data structures in which addition of new elements is accompanied by equal number of removals from the other end. There are two types of operations in Stack: 堆棧:基于FILO(先進先出)和LIFO(先進先出)的原理,堆棧是線性數據結構,其中添加新元素時會從另一端進行相同數量的刪除。 Stack中有兩種類型的操作:
a) Push — To add data into the stack.
a)推入—將數據添加到堆棧中。
b) Pop — To remove data from the stack.
b)Pop(彈出)—從堆棧中刪除數據。

We can implement stacks using modules and data structures from the Python library, namely — list, collections.deque, queue.LifoQueue.
我們可以使用Python庫中的模塊和數據結構來實現堆棧,即list,collections.deque,queue.LifoQueue。
2. Queue: Queue is a linear data structure which is based on the First in First out principle (FIFO). The data which is entered first will be accessed first. Operations on a queue can be performed from both ends, head and tail. En-queue and De-queue are terms for operations used to add or delete items from a queue. Similar to Stacks, we can implement stacks using modules and data structures from the Python library, namely — list, collections.deque.
2.隊列:隊列是一種線性數據結構,它基于先進先出原則(FIFO)。 首先輸入的數據將被首先訪問。 隊列的操作可以從頭和尾的兩端進行。 入隊和出隊是用于在隊列中添加或刪除項目的操作的術語。 與堆棧類似,我們可以使用Python庫中的模塊和數據結構(即list,collections.deque)實現堆棧。

3. Tree: Trees are no-linear data structures consisting of roots and nodes. The point of origination of the data is termed as the parent node and every other node arising subsequently has is a child node. The last nodes are the leaf nodes. The level of the nodes shows the depth of information in a tree.
3.樹:樹是由根和節點組成的非線性數據結構。 數據的起源點稱為父節點,隨后出現的每個其他節點都有一個子節點。 最后的節點是葉節點。 節點的級別顯示樹中信息的深度。

4. Graph: A graph in python typically store data collection of points called vertices (nodes) and edges (edges). A graph can be represented using the python dictionary data types. The keys of the dictionary are represented as vertices and the values represent the edges between the vertices.
4.圖形:Python中的圖形通常存儲稱為頂點(節點)和邊(edge)的點的數據收集。 可以使用python字典數據類型表示圖形。 字典的鍵表示為頂點,值表示頂點之間的邊。

Data structures help organizing information and whether you are a novice or a programming veteran, you can’t ignore the crucial concepts surrounding data structures.
數據結構有助于組織信息,無論您是新手還是編程老手,都不能忽略圍繞數據結構的關鍵概念。
For a more exhaustive coverage of the different data structures used in Python, refer to the following links:
有關Python中使用的不同數據結構的更詳盡介紹,請參見以下鏈接:
· The official Python documentation for lists, dictionaries, and tuples
·有關列表 , 字典和元組的官方Python文檔
· The book A Byte of Python.
·《 Python字節 》一書。
· https://docs.python.org/3/tutorial/datastructures.html
· https://docs.python.org/3/tutorial/datastructures.html
翻譯自: https://towardsdatascience.com/data-structures-in-python-a-brief-introduction-b4135d7a9b7d
python中定義數據結構
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/388218.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/388218.shtml 英文地址,請注明出處:http://en.pswp.cn/news/388218.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!