面向对象的Python - 数据结构

从语法的角度来看,Python数据结构非常直观,它们提供了大量的操作选择.您需要选择Python数据结构,具体取决于数据涉及的内容,是否需要修改,或者是否是固定数据以及需要哪种访问类型,例如在开头/结尾/随机等.

列表

List表示Python中最通用的数据结构类型.列表是一个容器,它在方括号之间包含逗号分隔值(项或元素).当我们想要处理多个相关值时,列表很有用.由于列表将数据保持在一起,我们可以一次对多个值执行相同的方法和操作.列表索引从零开始,与字符串不同,列表是可变的.

数据结构 - 列表

>>>
>>> # Any Empty List
>>> empty_list = []
>>>
>>> # A list of String
>>> str_list = ['Life', 'Is', 'Beautiful']
>>> # A list of Integers
>>> int_list = [1, 4, 5, 9, 18]
>>>
>>> #Mixed items list
>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>> # To print the list
>>>
>>> print(empty_list)
[]
>>> print(str_list)
['Life', 'Is', 'Beautiful']
>>> print(type(str_list))
<class 'list'>
>>> print(int_list)
[1, 4, 5, 9, 18]
>>> print(mixed_list)
['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']

访问Python列表中的项目

列表中的每个项目都分配了一个数字 - 即该数字的索引或位置.索引总是从零开始,第二个指数是一个等等.要访问列表中的项目,我们可以在方括号内使用这些索引号.请注意以下代码,例如 :

>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>>
>>> # To access the First Item of the list
>>> mixed_list[0]
'This'
>>> # To access the 4th item
>>> mixed_list[3]
18
>>> # To access the last item of the list
>>> mixed_list[-1]
'list'

空对象

空对象是最简单和最多的基本的Python内置类型.我们已多次使用它们而没有注意到,并将它扩展到我们创建的每个类.编写一个空类的主要目的是暂时阻止某些东西,然后扩展并添加一个行为.

向类中添加行为意味着用以下内容替换数据结构一个对象并更改对它的所有引用.因此,在创建任何内容之前检查数据是否很重要,无论它是伪装的对象.请注意以下代码以便更好地理解:

>>> #Empty objects
>>>
>>> obj = object()
>>> obj.x = 9
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
obj.x = 9
AttributeError: 'object' object has no attribute 'x'

所以从上面我们可以看到无法在直接实例化的对象上设置任何属性.当Python允许对象具有任意属性时,需要一定量的系统内存来跟踪每个对象具有的属性,
存储属性名称及其值.即使没有存储任何属性,也会为潜在的新属性分配一定量的内存.

因此,默认情况下,Python会禁用对象和其他几个内置函数的任意属性.

>>> # Empty Objects
>>>
>>> class EmpObject:
    pass
>>> obj = EmpObject()
>>> obj.x = 'Hello, World!'
>>> obj.x
'Hello, World!'

因此,如果我们想要将属性组合在一起,我们可以将它们存储在空对象中如上面的代码所示.但是,并不总是建议使用此方法.记住
只有在你想同时指定数据和
行为时才能使用类和对象.

元组

元组与列表类似,可以存储元素.但是,它们是不可变的,因此我们无法添加,删除或替换对象.元组提供的主要好处是因为它的不变性是我们可以将它们用作字典中的键,或者在
对象需要哈希值的其他位置.

使用元组存储数据,而不是行为.如果您需要行为
操纵元组,则需要将元组传递给执行操作的函数(或另一个
对象上的方法).

由于元组可以充当字典键,因此存储的值彼此不同.我们可以通过用逗号分隔值来创建元组.元组用括号括起来但不是强制性的.以下代码显示了两个相同的分配.

>>> stock1 = 'MSFT', 95.00, 97.45, 92.45
>>> stock2 = ('MSFT', 95.00, 97.45, 92.45)
>>> type (stock1)
<class 'tuple'>
>>> type(stock2)
<class 'tuple'>
>>> stock1 == stock2
True
>>>

定义元组

元组与list非常相似,只是整个元素集用括号括起来方括号.

就像切片列表一样,你会得到一个新的列表,当你对一个元组进行切片时,你得到一个新的
元组.

>>> tupl = ('Tuple','is', 'an','IMMUTABLE', 'list')
>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl[0]
'Tuple'
>>> tupl[-1]
'list'
>>> tupl[1:3]
('is', 'an')

Python元组方法

以下代码显示了Python元组中的方法 :

>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl.append('new')
Traceback (most recent call last):
   File "<pyshell#148>", line 1, in <module>
      tupl.append('new')
AttributeError: 'tuple' object has no attribute 'append'
>>> tupl.remove('is')
Traceback (most recent call last):
   File "<pyshell#149>", line 1, in <module>
      tupl.remove('is')
AttributeError: 'tuple' object has no attribute 'remove'
>>> tupl.index('list')
4
>>> tupl.index('new')
Traceback (most recent call last):
   File "<pyshell#151>", line 1, in <module>
      tupl.index('new')
ValueError: tuple.index(x): x not in tuple
>>> "is" in tupl
True
>>> tupl.count('is')
1

从上面显示的代码中,我们可以理解元组是不可变的,因此 :

  • 无法向元组添加元素.

  • 无法追加或扩展某种方法.

  • 无法删除来自元组的元素.

  • 元组有删除或弹出方法.

  • 计数和索引是元组中可用的方法.

Dictionary

Dictionary是Python的内置数据类型之一,它定义了键和值之间的一对一关系
.

定义字典

观察以下代码以了解有关定义字典的信息;

>>> # empty dictionary
>>> my_dict = {}
>>>
>>> # dictionary with integer keys
>>> my_dict = { 1:'msft', 2: 'IT'}
>>>
>>> # dictionary with mixed keys
>>> my_dict = {'name': 'Aarav', 1: [ 2, 4, 10]}
>>>
>>> # using built-in function dict()
>>> my_dict = dict({1:'msft', 2:'IT'})
>>>
>>> # From sequence having each item as a pair
>>> my_dict = dict([(1,'msft'), (2,'IT')])
>>>
>>> # Accessing elements of a dictionary
>>> my_dict[1]
'msft'
>>> my_dict[2]
'IT'
>>> my_dict['IT']
Traceback (most recent call last):
   File "<pyshell#177>", line 1, in <module>
   my_dict['IT']
KeyError: 'IT'
>>>

从上面的代码我们可以看出:

  • 首先,我们创建一个包含两个元素的字典,并将其分配给变量 my_dict .每个元素都是一个键值对,整个元素集是用大括号括起来的
    .

  • 数字 1 是键, msft 是其值.同样, 2 是关键, IT 是其
    值.

  • 您可以按键获取值,但反之亦然.因此,当我们尝试 my_dict ['IT'] 时,
    会引发异常,因为 IT 不是密钥.

修改字典

观察以下代码,了解修改字典和减号;

>>> # Modifying a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'IT'}
>>> my_dict[2] = 'Software'
>>> my_dict
{1: 'msft', 2: 'Software'}
>>>
>>> my_dict[3] = 'Microsoft Technologies'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}

从上面的代码我们可以观察到那个 :

  • 你不能在字典中有重复的键.更改现有密钥的值将删除旧值.

  • 您可以随时添加新的键值对.

  • 字典在元素之间没有顺序概念.它们是简单的无序集合.

在字典中混合数据类型

观察以下代码了解如何在字典中混合数据类型 :

>>> # Mixing Data Types in a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}
>>> my_dict[4] = 'Operating System'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>> my_dict['Bill Gates'] = 'Owner'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}

从上面的代码我们可以观察到 :

  • 不只是字符串,但字典值可以是任何数据类型,包括字符串,整数,包括字典本身.

  • 与字典值不同,字典键更受限制,但可以是字符串,整数或任何其他类型.

从词典中删除项目

请遵守以下代码以了解有关从字典中删除项目的信息 :

>>> # Deleting Items from a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}
>>>
>>> del my_dict['Bill Gates']
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>>
>>> my_dict.clear()
>>> my_dict
{}

从上面的代码我们可以观察到 :

  • del : 允许您按键从字典中删除单个项目.

  • 清除 : 删除字典中的所有项目.

设置

Set()是一个无序集合没有重复的元素.虽然单个项目是不可变的,但设置本身是可变的,即我们可以在集合中添加或删除元素/项目.我们可以使用set来执行诸如union,intersection等数学运算.

虽然通常可以使用树来实现集合,但是在Python中设置可以使用哈希表来实现.这允许它高度优化的方法来检查集合中是否包含特定的
元素

创建集合

集合是通过将所有项目(元素)放在花括号 {} 中,用逗号分隔或使用内置函数 set()创建.请注意以下几行代码 :

>>> #set of integers
>>> my_set = {1,2,4,8}
>>> print(my_set)
{8, 1, 2, 4}
>>>
>>> #set of mixed datatypes
>>> my_set = {1.0, "Hello World!", (2, 4, 6)}
>>> print(my_set)
{1.0, (2, 4, 6), 'Hello World!'}
>>>

集合的方法

观察以下代码以了解有关集合的方法;

>>> >>> #METHODS FOR SETS
>>>
>>> #add(x) Method
>>> topics = {'Python', 'Java', 'C#'}
>>> topics.add('C++')
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>>
>>> #union(s) Method, returns a union of two set.
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>> team = {'Developer', 'Content Writer', 'Editor','Tester'}
>>> group = topics.union(team)
>>> group
{'Tester', 'C#', 'Python', 'Editor', 'Developer', 'C++', 'Java', 'Content
Writer'}
>>> # intersets(s) method, returns an intersection of two sets
>>> inters = topics.intersection(team)
>>> inters
set()
>>>
>>> # difference(s) Method, returns a set containing all the elements of
invoking set but not of the second set.
>>>
>>> safe = topics.difference(team)
>>> safe
{'Python', 'C++', 'Java', 'C#'}
>>>
>>> diff = topics.difference(group)
>>> diff
set()
>>> #clear() Method, Empties the whole set.
>>> group.clear()
>>> group
set()
>>>

集合的运算符

观察以下代码以了解有关集合的运算符:

>>> # PYTHON SET OPERATIONS
>>>
>>> #Creating two sets
>>> set1 = set()
>>> set2 = set()
>>>
>>> # Adding elements to set
>>> for i in range(1,5):
   set1.add(i)
>>> for j in range(4,9):
   set2.add(j)
>>> set1
{1, 2, 3, 4}
>>> set2
{4, 5, 6, 7, 8}
>>>
>>> #Union of set1 and set2
>>> set3 = set1 | set2 # same as set1.union(set2)
>>> print('Union of set1 & set2: set3 = ', set3)
Union of set1 & set2: set3 = {1, 2, 3, 4, 5, 6, 7, 8}
>>>
>>> #Intersection of set1 & set2
>>> set4 = set1 & set2 # same as set1.intersection(set2)
>>> print('Intersection of set1 and set2: set4 = ', set4)
Intersection of set1 and set2: set4 = {4}
>>>
>>> # Checking relation between set3 and set4
>>> if set3 > set4: # set3.issuperset(set4)
   print('Set3 is superset of set4')
elif set3 < set4: #set3.issubset(set4)
   print('Set3 is subset of set4')
else: #set3 == set4
   print('Set 3 is same as set4')
Set3 is superset of set4
>>>
>>> # Difference between set3 and set4
>>> set5 = set3 - set4
>>> print('Elements in set3 and not in set4: set5 = ', set5)
Elements in set3 and not in set4: set5 = {1, 2, 3, 5, 6, 7, 8}
>>>
>>> # Check if set4 and set5 are disjoint sets
>>> if set4.isdisjoint(set5):
   print('Set4 and set5 have nothing in common\n')
Set4 and set5 have nothing in common
>>> # Removing all the values of set5
>>> set5.clear()
>>> set5 set()