Python 中的数据结构和算法 | 第一部分2024 年 8 月 29 日 | 阅读 16 分钟 数据结构和算法(DSA)是编程中的一个概念,每个程序员都必须精通,以便通过有效利用可用资源来创建代码。无论使用何种编程语言,DSA 都是一个更普遍的概念。本教程将使用 Python 编程语言介绍 DSA 的基础知识。 数据结构“数据 + 结构”说明了一切。数据结构就是构建数据的方式。它是一个存储单元,以程序员可以轻松访问的方式组织和存储数据。 在现实世界中,程序员/编码人员的工作涉及大量数据。当数据以正确的方式排列时,程序员可以轻松地分析和使用数据。除了组织数据外,数据结构还使数据的处理和访问变得容易。 本教程涵盖了 Python 的所有数据结构。有内置数据结构,也有用户自定义数据结构。我们先来看看内置的那些。 1. 列表 (Lists)列表就像一个动态且异构的数组。数组在像 C 这样的语言中使用。与数组不同,列表是动态大小的,可以存储不同类型的数据。它是 Python 中的序列数据类型之一。 关于列表的要点
最常用的函数和方法
示例 输出 Created lists: emptylist: [] mylist: [20, 20, 'H', 'Hello'] nestedlist: [[1, 2], [20, 20, 'H', 'Hello']] Concatenating mylist and nestedlist: [20, 20, 'H', 'Hello', [1, 2], [20, 20, 'H', 'Hello']] Repeating the elements of a list: [20, 20, 'H', 'Hello', 20, 20, 'H', 'Hello', 20, 20, 'H', 'Hello'] List as an input: Enter elements(separate by space):8 9 7 8 [8, 9, 7, 8] In the nested list: (Normal)nestedlist[0]: [1, 2] (Negative)nestedlist[-2]: [1, 2] Adding elements to the empty list: emptylist: [1, 3, 4, 5] Adding an index emptylist[1]: [1, 2, 3, 4, 5] Extending mylist with emptylist: None Using Slicing Slicing mylist[:]: [20, 20, 'H', 'Hello', 1, 2, 3, 4, 5] Reverse using slicing[::-1]: [5, 4, 3, 2, 1, 'Hello', 'H', 20, 20] Slicing using indices[1:3]: [20, 'H'] Creating a newlist[] using list comprehension: newlist with even elements in emptylist: [2, 4] Using functions: Length using len(): 9 Removing an element using remove: None Removing the last element using pop: 5 Using index(): 5 Using reverse on [1, 2, 3, 4, 5] : [5, 4, 3, 2, 1] 元组 (Tuples)元组就像一个不可变的列表。它也是 Python 中的一种序列数据类型,可以像列表一样存储不同数据类型的数据,但与列表不同的是,一旦创建元组,我们就不能更改它;如果我们尝试这样做,Python 会引发错误。 示例 输出 nestedtuple.append(1) AttributeError: 'tuple' object has no attribute 'append.'
示例 输出 [1, 2, 1] ([1, 2, 1], (1, 'h', 'Hello')) 关于元组的要点
最常用的函数和方法
示例 输出 Emptytuple: () mytuple: (1, 'h', 'Hello') nestedtuple: ([1, 2], (1, 'h', 'Hello')) By Tuple packing: (1, 'Hi') Using tuple(): (1, 2, 3) Tuple with one element: (1,) Concatenating nestedtuple and mytuple: ([1, 2], (1, 'h', 'Hello'), 1, 'h', 'Hello') Repeating the elements of a tuple: (1, 'h', 'Hello', 1, 'h', 'Hello', 1, 'h', 'Hello') Tuple as an input: Enter elements(separate by space):3 4 5 (3, 4, 5) Slicing mytuple[:]: (1, 'h', 'Hello') Reverse using slicing[::-1]: ('Hello', 'h', 1) Slicing using indices[1:3]: ('h', 'Hello') Accessing elements: In nestedtuple[0]: [1, 2] In nestedtuple[-2]: [1, 2] By tuple unpacking: 1 h Hello Using the built-in functions: Length of mytuple: 3 Sorting a tuple using sorted(): [0, 1, 2] Using max(): 23 Using min(): 1 Using sum(): 10 Using all(): False Using any(): True Using count(): 2 集合 (Sets)集合是唯一元素的集合,它不像列表和元组那样支持重复元素。关于集合的另一个重要点是它们是无序的,这使得使用索引访问它们的元素成为不可能。 关于集合的要点
输出 set1 = {[1, 2], 2, 3} TypeError: unhashable type: 'list' 集合上最常用的函数和方法
集合运算符
示例 输出 Creating a set: Empty set: set() Myset: {1, 2, 3} Nestedset: {3, (1, 2), 4} Removing duplicacy using set(): {1, 2} Enter elements: 10 11 12 inputset: {10, 11, 12} Frozen set: ({1, 2, 3, 4, 5}) Adding to emptyset: {'a'} Union of {1, 2, 3} and {3, (1, 2), 4} : {1, 2, 3, (1, 2), 4} Intersection of {1, 2, 3} and {3, (1, 2), 4} : {3} Difference of {1, 2, 3} and {3, (1, 2), 4} : {1, 2} Clearing emptyset: set() Membership operator to check if (1, 2) is in nestedset: True Equivalency on myset and nested set: False Subset operator to check if {1} is a subset of nestedset: False proper subset operator to check if {1} is a proper subset of nestedset: False Superset operator to check if nestedset is a superset of {1}: False proper superset operator to check if nestedset is a proper superset of {1}: False Elements in either myset or nestedset but not in both: {1, 2, (1, 2), 4}
字典字典是 {键: 值} 对的集合。键映射值,要访问值,我们需要在索引的位置使用键。它是一个无序的数据集合。 关于字典的要点
最常用的 dict 函数和方法
示例 输出 Enter keys: 1 2 3 Enter value for 1: a Enter value for 2: b Enter value for 3: c Created dictionaries: Emptydict: {} mydict1: {1: 'A', 2: 'B', 3: 'C'} mydict2: {4: 'D', 'E': 5} mydict3: {6: 'F', 7: 'G'} nesteddict: {1: {1: 'A', 2: 'B', 3: 'C'}, 2: {4: 'D', 'E': 5}} inputdict: {1: 'a', 2: 'b', 3: 'c'} Altering mydict2: {4: 'D', 5: 'E'} Adding elements to mydict3: {6: 'F', 7: 'G', 8: 'H', 9: ('I', 'J', 'K')} Using get() to access: mydict1.get(1): A Using keys() on {1: 'A', 2: 'B', 3: 'C'} : dict_keys([1, 2, 3]) using values() on {1: 'A', 2: 'B', 3: 'C'} : dict_values(['A', 'B', 'C']) Using items() on {1: 'A', 2: 'B', 3: 'C'} : dict_items([(1, 'A'), (2, 'B'), (3, 'C')]) Updating {1: 'A', 2: 'B', 3: 'C'} with {4: 'D', 5: 'E'} : {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'} Deleting a value using pop(): B {1: 'A', 3: 'C', 4: 'D', 5: 'E'} 字符串字符串是字节/字符的数组。在 C 语言中,我们将字符串声明为字符数组。在 Python 中,没有字符数据类型。字符确实存在,但它们被识别为长度为 1 的字符串。字符串是不可变的,这意味着一旦创建就不能修改。 关于字符串的要点
输出 TypeError: 'str' object does not support item assignment 示例 输出 TypeError: 'str' object doesn't support item deletion
示例:要表示一个浮点数,我们可以使用 %a.bf,其中 a 表示我们希望表示中有多少位数字,b 表示我们希望小数点后有多少位数字。 输出 0.26 示例 输出 Created strings: Hi Hi Hello Man The first character string1[0]: H The first character string[-2]: H Substrings of string3: string3[0:6]: Hello string3[-6:-1]: Ma Reversing using slicing-string3[::-1]: naM olleH Enter a string: What's up inputstring:: What's up Reassigning string2 to Hello: Present: Hi After reassigning: Hello Using escape sequences to escape single quotes, double quotes and backslashes Hi it's my pen I read a book called "It ends with us" yesterday The file is stored in the path: C:\Media\Documents\ Printing in a new line: Hi man Urging a tab space: Hi man The sum of 4 and 5: 9 The difference between 5 and 4: 9 The product of 4 and 5: 20 字符串是 Python 中最常用的数据类型之一。因此,Python 库中有足够多的关于字符串的概念、方法和函数。 一些非常重要的函数和方法
字节数组 (Bytearray)首先:1 字节 = 8 位(因系统而异)。字节数组,顾名思义,是字节的数组。它是字节的集合。它可以表示范围从 0 到 256 的整数。它是 Python 中的序列数据类型之一。字符串是 Unicode 字符的序列,而字节数组是字节的序列。 关于字节数组的要点
示例 输出 Created bytearray: bytearray(b'\x01\x02\x03\x04') Type: <class 'bytearray'> Elements of bytearray: 1 2 3 4 BA[2]: 3 Modifying BA[2] to 20: bytearray(b'\x01\x02\x06\x04') Adding elements: bytearray(b'\x01\x02\x06\x04\x07') bytearray()该函数可以构造一个字节数组对象,并将其他对象转换为字节数组对象。该函数的语法
示例 输出 bytearray(b'') 总结 在本教程中,我们学习了 Python 中的内置数据结构
在本教程的第二部分,我们将学习 Python 中的用户自定义数据结构,如链表、树和堆。 下一个主题Python 中的高斯消元法 |
我们请求您订阅我们的新闻通讯以获取最新更新。