目录

数据结构(Data Structures)

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

Lists

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!'

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

Tuples

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

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

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

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

定义一个元组

元组与列表非常相似,只是整个元素集括在括号中而不是方括号中。

就像切片列表一样,你得到一个新的列表,当你切片一个元组时,你得到一个新的元组。

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

Python Tuple Methods

以下代码显示了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

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

  • cannot将元素添加到元组。

  • cannot追加或扩展方法。

  • cannot从元组中删除元素。

  • 元组no删除或弹出方法。

  • Count和index是元组中可用的方法。

字典(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 - 允许您按键从字典中删除单个项目。

  • clear - 删除字典中的所有项目。

Sets

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

尽管通常可以使用树来实现集合,但是可以使用散列表来实现Python中的set。 这使它成为一种高度优化的方法,用于检查集合中是否包含特定元素

创建一个集合

通过将所有项(元素)放在花括号{} ,用逗号分隔或使用内置函数set()来创建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()
↑回到顶部↑
WIKI教程 @2018