python中定義數據結構_Python中的數據結構—簡介

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:

您可以在列表中添加,刪除或更改元素,而無需更改其標識。 以下是使用列表時常用的一些功能:

Image for post

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.

列表可以使用方括號索引,以檢索存儲在位置中的元素。 在列表中建立索引將返回該位置處的整個項目,而在字符串中,將返回該位置處的字符。

Image for post

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()刪除索引元素。

Image for post

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的最后一個值。

Image for post

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:

復制并處理列表:

Image for post

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,則默認情況下它將考慮第一個和最后一個元素。 我們在這里使用相同的概念。

Image for post

(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:

從元組創建和訪問元素:

Image for post

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.

您可以在字典中添加,刪除或更改現有的鍵值對。 下面提到的是使用字典執行的一些常用功能。

Image for post

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:

添加或更改鍵值對:

Image for post

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() —刪除兩個組中都存在的數據,并輸出兩個組中剩余的數據。

Image for post

用戶定義的數據結構的簡要概述 (A brief overview of user-defined data structures)

  1. 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(彈出)—從堆棧中刪除數據。

Image for post
Source: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
來源: https : //en.wikipedia.org/wiki/Stack_(abstract_data_type)

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)實現堆棧。

Image for post
Source: https://www.guru99.com/python-queue-example.html
資料來源: https : //www.guru99.com/python-queue-example.html

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.樹:樹是由根和節點組成的非線性數據結構。 數據的起源點稱為父節點,隨后出現的每個其他節點都有一個子節點。 最后的節點是葉節點。 節點的級別顯示樹中信息的深度。

Image for post
Source: https://sites.google.com/site/learnwithdatastructures/content/graphs
來源: https : //sites.google.com/site/learnwithdatastructures/content/graphs

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字典數據類型表示圖形。 字典的鍵表示為頂點,值表示頂點之間的邊。

Image for post
Source: https://codepumpkin.com/graph/
資料來源: https : //codepumpkin.com/graph/

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,一經查實,立即刪除!

相關文章

1206封裝電容在物料可靠性設計比較低

1206封裝電容在物料可靠性設計中是要盡力避免的,盡量選擇0805或1210。在現場中容易出現電容因斷裂而擊穿的情況。同時容易造成保險絲燒斷。轉載于:https://www.cnblogs.com/conglinlixian/p/10414877.html

Java開發中 Double 和 float 不能直接運算

不能直接運算 是因為計算機儲存浮點類型的數值使用指數和尾數來表示 這就意味著計算時會出現“精度缺失”的現象 為了解決這個問題 我們引入 java.math.BigDecimal類來進行精確計算。 具體如下: public class Arith { //加法運算 public static double add(dou…

Unity3D 場景與C# Control進行結合

楊航最近在自學Unity3D,打算使用這個時髦、流行、強大的游戲引擎開發一個三維業務展示系統,不過發現游戲的UI和業務系統的UI還是有一定的差別,很多的用戶還是比較習慣WinForm或者WPF中的UI形式,于是在網上搜了一下WinForm和Unity3…

數據質量提升_合作提高數據質量

數據質量提升Author Vlad Ri?cu?ia is joined for this article by co-authors Wayne Yim and Ayyappan Balasubramanian.作者 Vlad Ri?cu?ia 和合著者 Wayne Yim 和 Ayyappan Balasubramanian 共同撰寫了這篇文章 。 為什么要數據質量? (Why data quality?) …

黑魔法(method-swizzling)解決第三方庫引發的問題

需求 最近做一個項目中,有個需求,所有網絡請求,都不顯示 NetworkActvityIndicator(也就是狀態欄里旋轉的小圈圈). 解決過程1: 全局搜索 NetworkIndicator 關鍵字, 把所有涉及 NetworkIndicator …

Python 操作 MySQL 的5種方式(轉)

Python 操作 MySQL 的5種方式 不管你是做數據分析,還是網絡爬蟲,Web 開發、亦或是機器學習,你都離不開要和數據庫打交道,而 MySQL 又是最流行的一種數據庫,這篇文章介紹 Python 操作 MySQL 的5種方式,你可以…

unity3d 人員控制代碼

普通瀏覽復制代碼private var walkSpeed : float 1.0;private var gravity 100.0;private var moveDirection : Vector3 Vector3.zero;private var charController : CharacterController;function Start(){charController GetComponent(CharacterController);animation.w…

刪除wallet里面登機牌_登機牌丟失問題

刪除wallet里面登機牌On a sold-out flight, 100 people line up to board the plane. The first passenger in the line has lost his boarding pass but was allowed in regardless. He takes a random seat. Each subsequent passenger takes their assigned seat if availa…

PHP 備份還原 MySql 數據庫

原生 PHP 備份還原 MySql 數據庫 支持 MySql,PDO 兩種方式備份還原 php5.5 以上的版本建議開啟pdo擴展,使用 pdo 備份還原數據 備份文件夾 db_backup、import/log 文件要有讀寫權限環境版本 本人測試環境 php:5.5.38 /5.6.27-nts/7.0.12-nts; mysql: 5.5…

Java? 教程(Queue接口)

Queue接口 Queue是在處理之前保存元素的集合&#xff0c;除了基本的Collection操作外&#xff0c;隊列還提供額外的插入、刪除和檢查操作&#xff0c;Queue接口如下。 public interface Queue<E> extends Collection<E> {E element();boolean offer(E e);E peek();…

字符串操作截取后面的字符串_對字符串的5個必知的熊貓操作

字符串操作截取后面的字符串We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually come in a nice and clean format and require preprocessing to con…

最新 Unity3D鼠標滑輪控制物體放大縮小 [

var s 1.0;function Update () {var cube GameObject.Find("Cube");if(Input.GetAxis("Mouse ScrollWheel")){s Input.GetAxis("Mouse ScrollWheel");cube.transform.localScaleVector3(1*s,1*s,1*s);}}

sublime-text3 安裝 emmet 插件

下載sublime&#xff0c;http://www.sublimetext.com/ 安裝package control &#xff1a;https://packagecontrol.io/ins... 這個地址需要翻墻&#xff0c;訪問不了的可以看下圖 import urllib.request,os,hashlib; h 6f4c264a24d933ce70df5dedcf1dcaee ebe013ee18cced0ef93d…

數據科學家訪談錄 百度網盤_您應該在數據科學訪談中向THEM提問。

數據科學家訪談錄 百度網盤A quick search on Medium with the keywords “Data Science Interview” resulted in hundreds of Medium articles to help guide the reader from what concepts are covered to even specific company interviews ranging from Tesla, Walmart, …

unity3d]鼠標點擊地面人物自動走動(也包含按鍵wasdspace控制)

目錄(?)[-] 一效果圖二大概步驟 創建一個plane設置層為Terrain因為后面要判斷是否點擊的是這個層準備好人物模型并且將三個腳本拖放到人物上并且將動畫文件也拖放好記得看前面提醒哦 ThirdPersonCamera相當于smoothflowThirdPersonController修改版mouseMoveContr鼠標點擊人物…

uva 524(Prime Ring Problem UVA - 524 )

dfs練習題,我素數打表的時候ji了&#xff0c;一直沒發現實際上是ji*i&#xff0c;以后可記住了。還有最后一行不能有空格。。。昏迷了半天 我的代碼(紫書上的算法) #include <bits/stdc.h> using namespace std; int bk[110]; int num[110]; int vis[110]; int n; void d…

Web 開發基礎

一、 Web 開發簡介 最早的軟件都是運行在大型機上的&#xff0c;軟件使用者登陸到大型機上去運行軟件。后來隨著 PC 機的興起&#xff0c;軟件開始主要運行在桌面上&#xff0c;而數據庫這樣的軟件運行在服務器端&#xff0c;這種 Client/Server 模式簡稱 CS 架構。隨著互聯網的…

power bi函數_在Power BI中的行上使用聚合函數

power bi函數Aggregate functions are one of the main building blocks in Power BI. Being used explicitly in measures, or implicitly defined by Power BI, there is no single Power BI report which doesn’t use some sort of aggregate functions.聚合功能是Power BI…

關于如何在Python中使用靜態、類或抽象方法的權威指南

Python中方法的工作方式 方法是存儲在類屬性中的函數&#xff0c;你可以用下面這種方式聲明和訪問一個函數 >>> class Pizza(object):... def __init__(self, size):... self.size size... def get_size(self):... return self.size...>&…

廣義估計方程估計方法_廣義估計方程簡介

廣義估計方程估計方法A key assumption underpinning generalized linear models (which linear regression is a type of) is the independence of observations. In longitudinal data this will simply not hold. Observations within an individual (between time points) …