python了解
“Python Collection” also called “Python Data Structure” constitutes the core functionality of how data is stored and being assigned to a variable. All the examples we have seen until now in this series “Understanding Python” had one element assigned to a variable and the data type of the element was either an int, float, or a bool. Moving forward in this article, we will be focussing more on the “advanced data types”(list, tuple, set, and dictionary) wherein a variable can hold more than one element.
“ Python集合”(也称为“ Python数据结构”)构成了如何存储数据并将其分配给变量的核心功能。 到目前为止,在“理解Python”系列中,我们所看到的所有示例都为一个变量分配了一个元素,并且该元素的数据类型为int,float或bool。 在本文中,我们将进一步关注“高级数据类型”(列表,元组,集合和字典),其中一个变量可以包含多个元素。
Python Collections
Python集合
List清单Tuple元组Dictionary字典Set组We will be learning about each item in the contents for their accessing technique, properties, operations, and the methods they offer.
我们将学习内容中的每个项目,以了解它们的访问技术,属性,操作及其提供的方法。
1.List
1.清单
1.1) What is a “list”?
1.1)什么是“清单”?
The list is a collection in python that can hold multiple elements in it of different data types. It is denoted by square brackets[] and separate items in it with commas. A simple example is an empty list where an object is created as soon as you instantiate it by assigning it to a variable.
该列表是python中的一个集合,可以在其中包含不同数据类型的多个元素。 用方括号[]表示,并用逗号分隔各个项目。 一个简单的示例是一个空列表,在该列表中,通过将其分配给变量来实例化该对象即会立即创建该对象。
Figure[1] 图1]Now, let us see how we can have a list with multiple elements from different data types. In Figure[2], we have a list “a” that has elements of int(1,2,3,4), of string(“Python”), of float(45.67), and bool (True) data types in it.
现在,让我们看看如何拥有一个包含来自不同数据类型的多个元素的列表。 在图[2]中,我们有一个列表“ a”,该列表具有以下元素:int(1,2,3,4),字符串(“ Python”),float(45.67)和bool(True)数据类型它。
Figure[2] 图[2]Also, a list can hold another list inside it. It is called the “Nested list”. Figure[3] shows how my_list variable holds 2 lists [‘Pyhton’,’is Fun’] and [23,45,67]
同样,一个列表可以在其中包含另一个列表。 它被称为“嵌套列表”。 图[3]显示了my_list变量如何保存2个列表 ['Pyhton','is Fun']和[23,45,67]
Figure[3] 图[3]1.2) Accessing elements in a list
1.2)访问列表中的元素
Each element in the list is assigned with an index number and you can access the list items by referring to the index number. The index starts from “0”(from left to right). The first element has an index “0” and the last element has an index number “number of elements in the list -1”(since the index starts from 0). Every index is an integer and it helps us to just access any element with its integer index value.
列表中的每个元素都分配有一个索引号,您可以通过引用索引号来访问列表项。 索引从“ 0”开始(从左到右)。 第一个元素的索引为“ 0”,最后一个元素的索引号为“列表中的元素数-1”(因为索引从0开始)。 每个索引都是一个整数,它可以帮助我们访问具有其整数索引值的任何元素。
There are 2 ways in which you can access an element in the list. The first way is with positive indexing and the second way is with negative indexing. Let us take the example shown in Figure[2] and understand both techniques.
您可以通过两种方式访问列表中的元素。 第一种方法是使用正索引,第二种方法是使用负索引。 让我们以图[2]中所示的示例为例,并了解这两种技术。
Figure[4] 图[4]Here in the Figure[4], I have shown how an element is indexed in “positive indexing”(starts from “0” ), and in the case of “negative indexing”, the last element(from left) is assigned with -1. Now, let us see a few questions and put this concept into practice.
在图[4]中,我已经展示了如何在“正索引”(从“ 0”开始)中为一个元素建立索引,在“负索引”的情况下,最后一个元素(从左开始)被赋予- 1。 现在,让我们看看一些问题并将其付诸实践。
Hint: Refer to the table in Figure[4] and note down the index values from the positive indexing technique and as well as from the negative indexing technique. To get/retrieve the respective elements, just put the index value inside the square bracket after the variable name.(for example a[2] retrives the 3rd element from the list “a”).
提示:请参考图[4]中的表,并记下正索引技术和负索引技术的索引值。 要获取/获取各个元素,只需将索引值放在变量名称后面的方括号内即可(例如a [2]从列表“ a”中获取第三个元素)。
Consider the list “a” in Figure[2].
考虑图[2]中的列表“ a”。
Q 1) Print the first element in the list “a” ?(Use both the accessing techniques)
Q 1)打印列表“ a”中的第一个元素?(同时使用两种访问方法)
Figure[5] 图[5]Q 2) Print the last element in the list “a” ?(Use both the accessing techniques)
问题2)打印列表“ a”中的最后一个元素?(同时使用两种访问方法)
Figure[6] 图[6]Q 3) Print the element “Python” from the list “a” ?(Use both the accessing techniques)
问题3)从“ a”列表中打印元素“ Python”(同时使用两种访问方法)
Figure[7] 图[7]I am sure after seeing the above 3 questions, you would be confident in the access techniques used to extract or retrieve a certain element.
我确定看到上述3个问题后,您会对用于提取或检索特定元素的访问技术充满信心。
1.3) Slicing elements in a list
1.3)切片列表中的元素
To print a part of the list by selecting some elements, we use a slice operator (:) between the start and the end index values. Here, the index value on the left of the operator includes the element in its position in the sliced list whereas, the index value on the right of the operator excludes the element at the end index value. It considers the element before the element at the end index value. I know it seems a bit confusing to read through all this. Hence, refer to Figure[8] for a better understanding.
要通过选择一些元素来打印列表的一部分,我们在开始和结束索引值之间使用切片运算符(:)。 在此,运算符左侧的索引值包括元素在切片列表中的位置,而运算符右侧的索引值将元素排除在末尾索引值处。 它在结束索引值处考虑元素之前的元素。 我知道阅读所有这些内容似乎有些混乱。 因此,请参考图[8]以获得更好的理解。
Figure[8] 图[8]Consider the list “a” in Figure[2], let us put our learning on list slicing into practice by taking a few questions.
考虑图[2]中的列表“ a”,让我们通过提出一些问题将我们的学习成果应用于列表切片。
Hint: Again refer to the indexing table in Figure[4] for the index values and put them in the format shown in the figure[8].
提示:再次参考图[4]中的索引表以获取索引值,并将其放入图[8]中所示的格式中。
Q 1) Print/Slice the first 3 elements in the list “a”(Use both the accessing techniques).
Q 1)打印/切片列表“ a”中的前三个元素(使用两种访问方法)。
Figure[9] 图[9]Q 2) Print/Slice all the elements from 4 to True.
Q 2)打印/切片从4到True的所有元素。
Figure[10] 图[10]Q 3) Print all the elements of the list without using index values.
问3)不使用索引值就打印列表的所有元素。
Figure[11] 图[11]Q 4) Reverse the list elements using a negative indexing technique.
问题4)使用负索引技术反转列表元素。
Figure[12] 图[12]With these practice questions, I hope the concepts of accessing and slicing list are clear.
有了这些实践问题,我希望访问和切片列表的概念清晰明了。
NOTE: Accessing and Slicing techniques shown for lists are the same for Strings and Tuples. Hence, it very a important concept to understand and practice.
注意:列表显示的访问和切片技术与字符串和元组相同。 因此,理解和实践是一个非常重要的概念。
1.4) Mutability of Lists
1.4)列表的可变性
We can change/delete the elements of the list after we have created it. This is what makes list mutable. Let us see how we can realize with an example each. Refer to Figure[13].
创建列表后,我们可以更改/删除列表的元素。 这就是使列表可变的原因。 让我们看看如何通过一个示例来实现。 参见图[13]。
Figure[13] 图[13]General Properties of list: It is an ordered, indexed,heterogenous and mutable python collection. It can also hold duplicate elements.
list的常规属性:这是一个有序,索引,异构和可变的python集合。 它还可以容纳重复的元素。
1.5) Common “list” operations
1.5)常见的“列表”操作
There are 2 common list operations that we can perform on a list. They are, concatenation(+) and repetition(*). Let us understand with an example for each.
我们可以对列表执行2种常见的列表操作。 它们是concatenation(+)和repetition(*) 。 让我们以每个示例为例进行理解。
Concatenation(+):
串联(+):
The ‘+’ operator is used to combine(concatenate) two or more lists. Figure[14] shows how 2 lists “course1” and “course2” are concatenated using the “+” operator.
“ +”运算符用于合并(连接)两个或多个列表。 图[14]显示了如何使用“ +”运算符将2个列表“ course1”和“ course2”连接起来。
Figure[14] 图[14]Repetition(*):
重复(*):
The “*” operator is used to repeat a list ’n’ number of times. The ’n’ is specified by the user and has to be positive.
“ *”运算符用于重复列表“ n”次。 “ n”由用户指定,并且必须为正。
Figure[15] 图[15]1.6) List Methods
1.6)清单方法
The list collection has a wide range of methods to make the operations easier and flexible. We will see how to check for all the available methods and understand their working.
列表集合具有多种使操作更容易和灵活的方法。 我们将看到如何检查所有可用方法并了解其工作原理。
It is a whole lot easier to learn methods while working with “Jupyter” as it lets you research for available methods in just a line. i.e dir(list). After running it, the output is a list of all the available methods in python for a certain version. Refer to Figure[16] and you will find all the list methods starting from “append” to “sort”.
与“ Jupyter”一起工作时,学习方法要容易得多,因为它使您可以在线研究可用的方法。 即目录(列表)。 运行它之后,输出是特定版本的python中所有可用方法的列表。 参考图[16],您将找到所有从“追加”到“排序”的列表方法。
Figure[16] 图[16]Here is a brief description of what each of the built-in list methods does.
这是每个内置列表方法的简要说明。
Figure[17] 图[17]Let us some examples and understand how these methods are realized. I have commented appropriately as these are self-explanatory.
让我们来看一些例子,并了解如何实现这些方法。 我已经做出了适当的评论,因为这些都是不言自明的。
append and extend:
追加和扩展:
The method list.append(element) will add the element at the end of a list. It can only add one element to the list. To add more elements, we use the method “extend”.
方法list.append(element)将元素添加到列表的末尾。 它只能向列表添加一个元素。 要添加更多元素,我们使用“ extend ”方法。
Figure[18] 图[18]clear:
明确:
The clear method resets the list to an empty state.
clear方法将列表重置为空状态。
Figure[19] 图[19]copy:
复制:
This method returns a shallow copy of the list. That means it does not create a new object for the copied list instead it creates a reference to the copied list.
此方法返回列表的浅表副本。 这意味着它不会为复制列表创建新对象,而是会创建对复制列表的引用。
Consider the example in Figure[20]. “new_list” is assigned with a shallow copy of the list “List”. Here, upon adding a new element “pig”, only the original list “List” will be updated not the one which is shallowly copied(new_list).
考虑图[20]中的示例。 “ new_list”被分配了列表“ List”的浅表副本。 在此,在添加新元素“猪”时,仅原始列表“列表”将被更新,而不是浅表复制的列表(new_list)。
Figure[20] 图[20]count:
计数:
It returns the number of occurrences of the specified object in the list.
它返回列表中指定对象的出现次数。
Figure[21] 图[21]index:
指数:
It returns the lowest index in the list that the object appears.
它返回该对象出现的列表中的最低索引。
Figure[21] 图[21]insert:
插入:
The object is inserted into the list at the specified index.
该对象将以指定的索引插入列表。
Figure[22] 图[22]pop:
流行:
It removes and returns the last object of the list.
它删除并返回列表的最后一个对象。
Figure[22] 图[22]remove:
去掉:
It removes the specified object from the list.
它从列表中删除指定的对象。
Fiigure[23] 图[23]reverse:
逆转:
It reverses the list.
它会反转列表。
Figure[24] 图[24]sort:
分类:
It sorts the list in ascending order.
它以升序对列表进行排序。
Figure[25] 图[25]1.7) Some common built-in functions that work on the list( also works with set, tuple)
1.7)在列表上可用的一些常见内置函数(也可以与set,tuple一起使用)
len:
伦:
This function returns the size of a list.
此函数返回列表的大小。
sum:
和:
It adds all the elements in the list and returns an aggregated sum value. It only works when all the elements are either int or float.
它将列表中的所有元素相加并返回汇总的总和值。 仅当所有元素都是int或float时才起作用。
min and max:
最小和最大:
They return the smallest and largest element in the list. Again, it only works when all the elements are either int or float.
它们返回列表中的最小和最大元素。 同样,它仅在所有元素均为int或float时起作用。
Figure[26] 图[26]Note: If you are stuck to know what a function or a method does, just type the help( function_name) and you will be able to see the description. If the method belongs to a certain class then, you have to include as help(class.method_name). For example, help(list.clear) gives the method description of “clear” method of the class “list”.
注意:如果您想知道函数或方法的作用,只需键入help(function_name) ,您将能够看到描述。 如果该方法属于某个类,则必须将其包括为help(class.method_name) 。 例如, help(list.clear)给出类“ list”的“ clear”方法的方法描述。
2. Tuple
2.元组
2.1) What is a “Tuple”?
2.1)什么是“元组”?
It is another python collection of elements where the elements are separated by commas inside round brackets ( ). Let us see how we can create different tuples in the following Figure[27].
这是另一个python元素集合,其中的元素用圆括号()内的逗号分隔。 在下图[27]中,让我们看看如何创建不同的元组。
Figure[27] 图[27]2.2) Accessing and Slicing a tuple
2.2)访问和切片元组
The techniques used to access and slice a list is exactly used for tuple as well. Please refer to 1.2 & 1.3 parts of this article for more details.
用于访问和切片列表的技术也正好用于元组。 有关更多详细信息,请参阅本文的1.2和1.3部分。
2.3) Mutability in a tuple
2.3)元组中的可变性
Tuples are immutable, unlike lists. They can not be modified after their creation. However, we can change the elements of nested items in a tuple that are mutable. Refer Figure[28] and Figure[29] for a better understanding.
与列表不同,元组是不可变的。 创建后无法对其进行修改。 但是,我们可以更改可变元组中嵌套项目的元素。 有关更好的理解,请参见图[28]和图[29]。
Figure[28] 图[28]The deletion of an element of a tuple is not possible. However, deleting the entire tuple is possible.
无法删除元组的元素。 但是,可以删除整个元组。
Figure[29] 图[29]General properties of a Tuple: It is indexed,ordered,immutable and heterogenous.
元组的一般属性:它是索引的,有序的,不可变的和异构的。
2.4) Tulple built-in methods
2.4)Tulple内置方法
We have 2 python built-in methods for the tuple. Both are covered in the list. Let us see how they work over a tuple.
我们为元组提供了2个python内置方法。 两者都在列表中。 让我们看看它们如何在元组中工作。
count:
计数:
It returns the number of times a specified element occurs in a tuple.
它返回指定元素在元组中出现的次数。
Figure[30] 图[30]index:
指数:
It searches the tuple for the first occurrence of a specified element and returns the index value for that particular position.
它在元组中搜索指定元素的首次出现,并返回该特定位置的索引值。
Figure[31] 图[31]3. Dictionary
3.字典
3.1) What is a “Dictionary”?
3.1)什么是“词典”?
Python dictionary is an unordered collection of elements. It maps keys to values and these key-value pairs provide a useful way to store data in python. Separate the keys from values with a colon(:), and a pair from another by a comma(,). Put it all in curly braces{ } as shown in Figure[32].
Python字典是元素的无序集合。 它将键映射到值,并且这些键值对提供了一种在python中存储数据的有用方法。 用冒号(:)分隔键和值,并用逗号(,)分隔键。 如图[32]所示,将其全部放在花括号{}中。
Figure[32] 图[32] Figure[33] 图[33]In the above figure “Rohit”, “Virat” and “Shikhar” are the keys, and 145,78,56 are their respective values.
在上图中,“ Rohit”,“ Virat”和“ Shikhar”是键,而145,78,56是它们各自的值。
3.2) Accessing values in a dictionary
3.2)访问字典中的值
Use the key inside the square brackets to access the elements from a dictionary. Also, you can use the get() method which we will see in dictionary methods.
用方括号中的键从字典访问的元素。 另外,您可以使用get()方法,该方法将在字典方法中看到。
Figure[34] 图[34]3.3) Mutability in a dictionary
3.3)字典中的可变性
Once a dictionary is created, only the values in it can be modified not the keys. Hence, keys are immutable and values are mutable.
创建字典后,只能修改其中的值,不能修改键。 因此,键是不可变的,值是可变的。
Figure[35] 图[35]Add an item to the dictionary by using a new index key and assign a value to it.
通过使用新的索引键将一项添加到字典中,并为其分配一个值。
Figure[36] 图[36]3.4) Built-in Methods in the dictionary
3.4)字典中的内置方法
Figure[37] shows the available built-in dictionary methods. Let us see an example for each and understand.
图[37]显示了可用的内置字典方法。 让我们为每个例子看一个并理解。
Figure[37] 图[37]dict.clear():
dict.clear():
It is used to delete all the items of the dictionary.
它用于删除字典中的所有项目。
Figure[38] 图[38]dict.copy():
dict.copy():
It returns a shallow copy of the dictionary.
它返回字典的浅表副本。
Figure[39] 图[39]dict.fromkeys():
dict.fromkeys():
Create a new dictionary from the iterable(list or tuple)with the values equal to value.
从iterable(列表或元组)创建一个新字典,其值等于value。
Figure[40] 图[40]dict.get(key):
dict.get(key):
It is used to get the value specified for the passed key.
它用于获取为传递的密钥指定的值。
Figure[41] 图[41]dict.items():
dict.items():
It returns all the key-value pairs as a tuple.
它以元组的形式返回所有键值对。
Figure[42] 图[42]dict.keys():
dict.keys():
It returns all the keys of the dictionary.
它返回字典的所有键。
Figure[43] 图[43]dict.setdefault():
dict.setdefault():
It is used to set the key to the default value if the key is not specified in the dictionary.
如果未在字典中指定密钥,则用于将密钥设置为默认值。
Figure[44] 图[44]dict.update():
dict.update():
It updates the dictionary by adding the key-value pair of another dictionary to this dictionary.
它通过将另一个字典的键-值对添加到该字典来更新字典。
Figure[45] 图[45]dict.values():
dict.values():
It returns all the values of the dictionary
它返回字典的所有值
Figure[46] 图[46]Note: Each key should be unique. If you ever try to create a dictionary with duplicate keys, the last value of the key will be retained and the first value will be excluded. Refer to Figure[47].
注意:每个键应该是唯一的。 如果尝试使用重复的键创建字典,则键的最后一个值将保留,而第一个值将被排除。 参见图[47]。
Figure[47] 图[47]4. Set
4.设置
4.1) What is a “set”?
4.1)什么是“集合”?
The set is a collection of unique and unordered elements. It is denoted by { } with comma-separated elements inside the curly brackets. It also holds elements from other data types which makes it heterogeneous. The set is a mutable collection where the elements are not indexed, hence they can not be accessed. Let us now see some examples of creating a set in Figure[48].
该集合是唯一和无序元素的集合。 用{}表示,并在大括号内使用逗号分隔的元素。 它还包含来自其他数据类型的元素,这使其变得异构。 该集合是一个可变集合,其中的元素未编制索引,因此无法访问它们。 现在让我们来看一些在Figure [48]中创建集合的示例。
Figure[48] 图[48]4.2) Set built-in functions
4.2)设置内置功能
To get all the available methods that are in sets, just type dir(set) and it lists all the available methods. Let us see some of them with an example.
要获取集合中所有可用的方法,只需键入dir(set),它会列出所有可用的方法。 让我们来看一个例子。
add and update:
添加和更新:
The “add” method is used to add an element to an existing set whereas the “update” method is used to add more than one element to an existing set. Figure[49] shows the difference between the add and the update method.
“添加”方法用于将元素添加到现有集中,而“更新”方法用于将多个元素添加到现有集中。 图[49]显示了add和update方法之间的区别。
Figure[49] 图[49]remove:
去掉:
It removes an element specified by the user.
它删除用户指定的元素。
Figure[50] 图[50]pop:
流行:
It removes a random element from the set. It raises a KeyError if the set is empty.
它从集合中删除一个随机元素。 如果集合为空,则引发KeyError 。
Figure[51] 图[51]4.3) Set Operations
4.3)设置操作
Set provides a useful number of operations to be performed on 2 or more sets. Let us see how we can quickly understand each of them.
Set提供了许多有用的操作,可以对2个或更多的Set执行。 让我们看看我们如何快速理解它们中的每一个。
Checking if 2 sets are disjoint:
检查2套是否不相交:
A disjoint set: The two sets without any common elements.
不相交的集合:这两个集合没有任何共同的元素。
Figure[52] 图[52]Checking for a subset:
检查子集:
Use the issubset() method to check whether all elements of a set are contained in another set.
使用issubset()方法检查一个集合中的所有元素是否都包含在另一个集合中。
Figure[53] 图[53]Set Union:
设置联盟:
Use the union() method to compute the union of two or more sets.
使用union()方法来计算两个或更多集合的并集。
Figure[54] 图[54]Set Intersection:
设置交叉点:
Use the instersection() method to find the common elements of two or more sets.
使用instersection()方法查找两个或更多集合的公共元素。
Figure[55] 图[55]Set Difference:
设置差异:
Use the difference() method to compute the difference between two or more sets. It returns a new set containing all items from the first set that are not in the other set.
使用difference()方法来计算两个或更多集合之间的差异。 它返回一个新集合,其中包含来自第一个集合的所有不在另一个集合中的项目。
Figure[56] 图[56]Conclusion:
结论:
If you are in this line, it means that you have now successfully learned all the basic aspects of “python collection”. I have tried to include as many examples as possible to make reading easy. I will continue to write on the other python programming aspects in the upcoming articles. Happy reading!.
如果您处在这一行中,则意味着您现在已经成功学习了“ python集合”的所有基本方面。 我尝试包含尽可能多的示例以使阅读变得容易。 在接下来的文章中,我将继续在其他Python编程方面进行写作。 祝您阅读愉快!
翻译自: https://medium.com/towards-artificial-intelligence/understanding-python-part-3-b74ccb5701e3
python了解
